user3150201
user3150201

Reputation: 1947

Error when running JAR file

I finished a Java game I was working on. Tried to run it by double clicking the icon, didn't run. It runs fine in Eclipse.

Tried to run it from the command line. Gave me a NullPointerException, on some image resource I have in a folder called sprites in the src folder, inside Eclipse.

For some reason, when running it outside Eclipse, it doesn't find this resource.

Any suggestions?

EDIT

I use Windows XP. The IDE is Eclipse. Inside Eclipse, as I said, there's no problem. I use the following command to use the image resources:

Image image = new ImageIcon(this.getClass().getResource("/sprites/picture.PNG").getImage();

I checked inside the JAR, all resources are inside.

sprites is a folder inside src. So as far as I see, it should work. What's the problem?

Upvotes: 2

Views: 756

Answers (3)

Andrew Gies
Andrew Gies

Reputation: 719

Try MyClass.class.getResourceAsStream(). When you specify a path for the image using this method, the path is relative to the MyClass.class compiled file. Not your .java file, or your project directory.

For example if your file system looks like this:

+ Project Folder
|
-> + src
|  |
|  -> MyClass.java
|
-> + bin
   |
   -> MyClass.class
   -> myImage.png

Then you would use the following code to retrieve the BufferedImage from myImage.png:

InputStream stream = MyClass.class.getResourceAsStream("myImage.png");
BufferedImage myImage = ImageIO.read(stream);

Remember, when using the getResourceAsStream() method, you must specify the path relative to the .class file, NOT the .java file. Many IDE's put them in separate places.

You can get as advanced as you want to with the file system, but just make sure all your paths are right. For example, if your file system looked like this:

+ Project Folder
|
-> + src
|  |
|  -> MyClass.java
|
-> + bin
   |
   -> MyClass.class
   -> + Sprites
      |
      -> + Images
         |
         -> myImage.png

You would just change the file path from myImage.png to Sprites/Images/myImage.png". Note the use of the file extension and the lack of a leading /.

Upvotes: 1

dooxe
dooxe

Reputation: 1490

If your sources are like that :

/src 
  /mypackage
      /myresourcespackage
          - Resources.java
          - image.png

You can load image.png using :

ImageIO.read(Resources.class.getResource("image.png"));

Upvotes: 1

venergiac
venergiac

Reputation: 7717

If the resource file is packaged into the jar file use

ClassLoader.getResourceAsStream or Class.getResourceAsStream

They are definitely the way to go for loading the resource data from classpath.

Upvotes: 0

Related Questions