Get file from project folder java

后端 未结 9 643
庸人自扰
庸人自扰 2020-12-24 06:56

I want to get File from project folder by using \"File class\" , How I can Do that ?

File file=new File(\"x1.txt\");
9条回答
  •  北海茫月
    2020-12-24 07:15

    If you are trying to load a file which is not in the same directory as your Java class, you've got to use the runtime directory structure rather than the one which appears at design time.

    To find out what the runtime directory structure is, check your {root project dir}/target/classes directory. This directory is accessible via the "." URL.

    Based on user4284592's answer, the following worked for me:

    ClassLoader cl = getClass().getClassLoader();
    File file = new File(cl.getResource("./docs/doc.pdf").getFile());
    

    with the following directory structure:

    {root dir}/target/classes/docs/doc.pdf
    

    Here's an explanation, so you don't just blindly copy and paste my code:

    • java.lang.ClassLoader is an object that is responsible for loading classes. Every Class object contains a reference to the ClassLoader that defined it and can fetch it with getClassLoader() method.
    • ClassLoader's getResource method finds the resource with the given name. A resource is some data that can be accessed by class code in a way that is independent of the location of the code.

提交回复
热议问题