Get file from project folder java

后端 未结 9 655
庸人自扰
庸人自扰 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:24

    Given a file application.yaml in test/resources

    ll src/test/resources/
    total 6
    drwxrwx--- 1 root vboxsf 4096 Oct  6 12:23 ./
    drwxrwx--- 1 root vboxsf    0 Sep 29 17:05 ../
    -rwxrwx--- 1 root vboxsf  142 Sep 22 23:59 application.properties*
    -rwxrwx--- 1 root vboxsf   78 Oct  6 12:23 application.yaml*
    -rwxrwx--- 1 root vboxsf    0 Sep 22 17:31 db.properties*
    -rwxrwx--- 1 root vboxsf  618 Sep 22 23:54 log4j2.json*
    

    From the test context, I can get the file with

    String file = getClass().getClassLoader().getResource("application.yaml").getPath(); 
    

    which will actually point to the file in test-classes

    ll target/test-classes/
    total 10
    drwxrwx--- 1 root vboxsf 4096 Oct  6 18:49 ./
    drwxrwx--- 1 root vboxsf 4096 Oct  6 18:32 ../
    -rwxrwx--- 1 root vboxsf  142 Oct  6 17:35 application.properties*
    -rwxrwx--- 1 root vboxsf   78 Oct  6 17:35 application.yaml*
    drwxrwx--- 1 root vboxsf    0 Oct  6 18:50 com/
    -rwxrwx--- 1 root vboxsf    0 Oct  6 17:35 db.properties*
    -rwxrwx--- 1 root vboxsf  618 Oct  6 17:35 log4j2.json*
    

提交回复
热议问题