JAR problem - images/sound

When I make a jar archive from my .class-files and the image and sound file I use in the program (all files in program root directory) and execute it, the image and sound are not loaded unless they are in the directory in which the jar-file is. That is, although they are inside the jar-file, they have to be in the same directory as the jar-file too.

I create the jar-file using (I’ve also tried . for the files to be included):

jar -cmf manifest.mf game.jar *.class image.gif sound.wav

And run it using (the program starts, only it doesn’t play the sound and doesn’t display the image):

java -jar game.jar

Anyone know what I’m doing wrong?

How are you accessing your sound/images files from code?

Kev

Like this:

img = Toolkit.getDefaultToolkit().getImage(“image.gif”);

and:

codeBase = new URL(“file:” + System.getProperty(“user.dir”) + “/”);
soundURL = new URL(codeBase,“sound.wav”);
theSound = Applet.newAudioClip(soundURL);

I think thats the problem. The method getImage(“image.gif”) access the image from the filesystem and so won’t check the jar. If you use


url = YourClass.class.getClassLoader().getResource("image.gif");
img = Toolkit.getDefaultToolkit().getImage(url);

Where “YourClass” is the class name of the current class that should work. Likewise for the sounds:


url = YourClass.class.getClassLoader().getResource("sound.wav");
theSound = Applet.newAudioClip(url);

Both of these access the resources via the class path, so if the jar is in the classpath it should work. Infact you can then put the resources wherever you like in the classpath (maybe another jar?).

Hope it helps,

Kev

It worked. Thanks! :slight_smile: