02100+02199 Indledende Programmering: Images etc. in <tt>jar</tt>-files

02100+02199  Indledende Programmering        Januar 2004
Images etc. in jar-files


Often a Java program uses images, soundclips and other auxilitary files that should go together with the program. If the program is packed in a jar-file and run out-of-the-jar by the command

java -jar jarfile
the auxiliary files within the jarfile cannot be accessed via normal Java file operations, since these operations will only see the file-system of the local machine.

Instead, the auxliary files will have to be accessed using the more general notion of a resource identified by URLs (Uniform Resource Locator). Resources are searched for by the class-loader using the classpath for its search. Using the java -jar jarfile command, the class-loader will use the jarfile as its classpath and this way, the auxliary files can be seen.

The simplest way to let the class-loader search for a resource is to use the method getResource(String) that is associated with the Class-object of the actual class. This method returns an URL (defined in the java.net package) which can be used instead of a file-name in many methods, for instance in the constructor for an ImageIcon.

If the actual class is C, a name can be looked up as a resource by:

java.net.URL res = C.class.getResource(name)
The name is searched for relative to the class C, unless it starts with an "/" in which case the search starts at the at the top of the classpath.

Example

As an example, consider resources.jar which can show an image and a text-file when running out-of-the-jar (java -jar resources.jar).

You may extract its contents by

jar xvf resources.jar
to see, how the auxiliary files are accessed in the class ccs.ImageInJAR.ImageInJARDriver.

Links

More information on use of images can be found here, including how to load images as resources.


Hans Henrik Løvengreen, Jan 15, 2004