Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java relative path start from my src folder

Tags:

java

I wanna use relative path start from my src folder to get file from resource folder.

File myFile = new File("/src/main/resources/filefolder/file.xml");

When I try this:

File myFile = new File("../src/main/resources/filefolder/file.xml");

Or this:

File myFile = new File("../../../../src/main/resources/filefolder/file.xml");

I get:

java.io.FileNotFoundException: /srv/../src/main/resources/filefolder/file.xml(No such file or directory)

My file structure:

-src
   -main
       -java
           -com.my.site
              -task
                 -MyClass.java
       -resources
like image 358
Olesia Ilchuk Avatar asked Dec 06 '25 08:12

Olesia Ilchuk


1 Answers

your path is correct, just add dot before src, to indicate that you are searching relative path to project root directory, in other case you'll search by absolute path

 File myFile = new File("./src/resources/filefolder/file.xml");

if doesn't work - try this:

File myFile = new File("src/resources/filefolder/file.xml");

anyway you can run this to check what is your root dir:

public static void main(String[] args) {
  System.out.println(new File("").getAbsolutePath());
}
like image 106
Vitaliy Moskalyuk Avatar answered Dec 08 '25 22:12

Vitaliy Moskalyuk