0

I'm working on a game in Java and it runs as expected in Eclipse but when I export it as an executable jar, I get a null pointer exception when I try to call the listFiles( ) method of the File class. Here is the code:

File Buffer = new File( "Resources/SpriteSheets" );

// Count how many sprite sheets there are
m_intTotalSheetCount = Buffer.listFiles( ).length;

Here's the error:

C:\Users\Joe>java -jar C:\Users\Joe\Documents\GameDevelopment\Game1.jar
Exception in thread "Thread-2" java.lang.NullPointerException
        at Graphics.CSpriteSheetLoader.<init>(CSpriteSheetLoader.java:25)
        at Graphics.CScreen.<init>(CScreen.java:36)
        at game.CGame.Initialize(CGame.java:107)
        at game.CGame.run(CGame.java:157)
        at java.lang.Thread.run(Thread.java:722)

I looked in the jar file and there isn't even a resource folder there, so I also tried File( "SpriteSheets" ), but I got the same error

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Joe Boris
  • 487
  • 3
  • 8
  • 15
  • Give us a listing of `C:\Users\Joe\Resources\SpriteSheets` – Ingo Jul 27 '13 at 22:43
  • 1
    I guess you are trying to load files from within the jar file: http://stackoverflow.com/questions/2815404/load-properties-file-in-jar – HectorLector Jul 27 '13 at 23:04
  • I have no folder called Resources in my Joe folder. Do you mean C:\Users\Joe\Documents\GameDevelopment\Game1.jar? Or do you mean the directory of the eclipse project? – Joe Boris Jul 27 '13 at 23:05
  • By the time of deployment, those resources will likely become an [tag:embedded-resource]. That being the case, the resource must be accessed by `URL` instead of `File`. See the [info page](http://stackoverflow.com/tags/embedded-resource/info) for the tag, for a way to form an `URL`. – Andrew Thompson Jul 28 '13 at 05:19

2 Answers2

0

You are trying to access a file that is not inside the jar file. If you include the resources folder with the jar. In other words place it within the same directory it should work.

Ex. If the jar is in the desktop the resource files must also be on the desktop

Bevilacqua
  • 465
  • 3
  • 8
  • 19
  • No, I'm trying to access a file inside the jar. Is there a different syntax for that? I confirmed the file is there: http://i.imgur.com/UCKPmSj.png – Joe Boris Jul 27 '13 at 23:23
0
  1. If the "Resources/SpriteSheets" directory inside Jar file

    this.getClass().getClassLoader().getResource()

    ClassLoader.getSystemResource

  2. If the "Resources/SpriteSheets" directory outside the jar file

    System.getProperty("user.dir")

to get the root directory(the executable jar dir),then you can do what you want.

PS:you should check Buffer.listFiles( ) == null

CHmoonKa
  • 181
  • 1
  • 12
  • Thanks, I realized yesterday that I can't make an instance of the File class with a resource inside the jar, so I just put the file outside the jar and that did the trick – Joe Boris Jul 28 '13 at 23:31