2

One year ago I've wrote JavaFX 2.0 application for my graduation work. But after one year pass I have a problem with code, that worked before.

So, in code I want to get folder and list it's files:

File dir = new File(getClass().getResource("media/images/backgrounds/").getPath()); 
File[] files = dir.listFiles();
for (File file : files) {
    list.add(file.toURI().toString());
}

and I'm getting java.lang.NullPointerException on line "for (File file : files) {"

System.out.print(getClass().getResource("media/images/backgrounds/").getPath());

returns file:/D:/JavafxApp1/JavafxApp/dist/run2054723721/JavafxApp.jar!/javafxapp/media/images/backgrounds/

I don't want make another method for reading files from stream from JAR file.This method of getting files have worked 100% one year ago, but why it doesn't work now? Thanks!

Gleb
  • 731
  • 1
  • 8
  • 14
  • 1
    You were likely using NetBeans to build your software. JavaFX projects in earlier NetBeans versions pre 7.2 just ran off of class files compiled to the file system. Later versions compile to a jar using JavaFX deployment tools. So your old code was wrong in that it should not have assumed that the resource was obtained using a file URL. – jewelsea Jan 16 '13 at 10:07
  • Wow, this is what I've searched! Thanks a lot, now it's clear!) – Gleb Jan 16 '13 at 11:50

2 Answers2

2

It won't work because your folder is in a jar. I suppose one year ago they were not. I think you don't need to have seperate code for the case where the directory is outside of a jar:

I found this example that shows how you can list the files of a directory using getResourceAsStream. Then, in turn, you could access these resources by getResourceAsStream. You will never know whether you were inside or outside a jar :-)

kutschkem
  • 7,826
  • 3
  • 21
  • 56
  • But how can you explain that is worked earlier?? Old version of JavaFX? But upgrades of versions usually is not so painful for old applications...Very strange situation. – Gleb Jan 12 '13 at 16:49
  • Actually, i have no clue, i can only suspect that you just ran it through Eclipse or another IDE and never had your app inside a jar before. – kutschkem Jan 12 '13 at 17:05
  • @ViralModi Thanks, I found another answer on StackOverflow to replace the previous link. The link should be working now. – kutschkem Sep 27 '19 at 07:23
2

Don't create a File it won't work for accessing resources inside jar.

getClass().getResource()

already returns you URL, so use that URL or another option is getResourceAsStream()

Nikolay Kuznetsov
  • 9,467
  • 12
  • 55
  • 101