Java : access project directory outside src

Viewed 4184

I want to retrieve files from the folder ressources/images/,so I do this in my Main.java :

URL url = getClass().getClassLoader().getResource("../ressources/images/");
File folder = new File(url.getFile());

File[] listOfFiles = folder.listFiles();

Here is the overall project hierarchy

   myGame
      - ressources
          -- images
              --- image1.jpg
              --- image2.jpg
              --- image3.jpg
      - src
          -- dvt
             --- Main.java

But I get this error at the 2nd line:

Exception in thread "JavaFX Application Thread" java.lang.NullPointerException

So I assume it couldn't find the directory.

Using an absolute path works fine, but not the relative one:

    File folder = new File("D:\\courses\\UE4\\projet2\\ressources\\images\\");
3 Answers
File folder = new File(System.getProperty("user.dir")+"/ressources/images");
File[] listOfFiles = folder.listFiles();

System.getProperty("user.dir") is the project folder, in your case myGame just append the remaning path and it will work

Related