1

Possible Duplicate:
load file within a jar

Finally, I made my jar file work almost correctly. Almost, because when I test it and launch just after creating jar file, a picture which is included in the archive appears. But when I move the jar file to any other directory and try to launch - I get an exception regarding missing picture (the application is still working though, but doesn't display that picture).

This is how it looks in my directory:

[aqv@voland Converter]$ ll
razem 112
-rw-rw-r--. 1 aqv aqv 51673 10-30 20:42 Converter.java
-rw-rw-r--. 1 aqv aqv    23 10-30 20:41 Converter.mf
-rw-rw-r--. 1 aqv aqv  1167 10-30 20:43 GBC.java
-rw-rw-r--. 1 aqv aqv  1023 10-30 20:58 ImagePanel.java
-rw-rw-r--. 1 aqv aqv 44729 10-30 20:35 programHelp.png
-rw-rw-r--. 1 aqv aqv  3713 10-30 20:43 SettingsManager.java
[aqv@voland Converter]$ 
[aqv@voland Converter]$ 

The picture file gets called from ImagePanel, programHelp is a string which is then passed to proper method:

public ImagePanel() {

    programHelp = "programHelp.png";

    try {
        helpImage = ImageIO.read(new File(programHelp));
    } catch (IOException e) {
        e.printStackTrace();
    }
}

As you can see, there are no directories specified, so I guess the main class should look for the image in the jar's main directory, shouldn't it?

I create the jar file in the following way (after compiling the files, of course):

[aqv@voland Converter]$ jar cvfm Converter.jar Converter.mf *.class *.png
[aqv@voland Converter]$ 

The picture file is visible inside the jar archive, among class files. My question: what is wrong with the image file placement in this case?

Community
  • 1
  • 1
AbreQueVoy
  • 1,748
  • 8
  • 31
  • 52

1 Answers1

4

Your program is only working by coincidence - it is actually loading the PNG from outside the JAR. You could test this by temporarily renaming the image but keeping the JAR in the directory, if you like.

To load resources from within a JAR, you need to use one of the getResource() methods of a Class object, rather than loading files directly.

You can still use ImageIO to load the data from the stream returned by getResourceAsStream(), for example. Something like the following:

InputStream is = this.getClass().getResourceAsStream("my.png");
helpImage = ImageIO.read(is);
DNA
  • 42,007
  • 12
  • 107
  • 146