Using Jar Files

You can read files and images and load classes from a jar file. In an application the jar file must be in your classpath. The simplest way to do this is as follows where the classpath includes the file foo.jar and the current directory. Note that if the class file App.class is in the jar file that the current directory doesn't need to be part of the class path since the java runtime will find the App.class file in the jar file.

java -cp foo.jar:. App

In an applet, the jar file is specified in the ARCHIVE tag of the html page, see this page for details.

Reading from a jar file

You can read images and files from a jar file. To do this you open the resource (an image, sound file, or whatever) either as a URL or as an input stream. Your program must be able to process data that's in one of these forms.

To get a gif image as URL, for example, you can write the code below.

URL u = this.getClass().getResource("image.gif");

Now your program can process the URL, see the java.net.URL API for details.

Alternatively, you can open the the resource as a stream.

InputStream in = this.getClass().getResourceAsStream("plainbogdict");

Now you can process this stream, e.g., by creating a BufferedReader around it, or using it as is.

Executable JAR files

You can create an executable jar file, so that running it is done with a command like:
  java -jar snews.jar

To do this you create a single line file that will be part of the jar file manifest. Using your favorite text editor create a file with any name, I'll use the name mainFile in the example. This file has single line that provides the class containing the public static void main function that launches the program.

   Main-Class: snews.MainApp

In this example I'm assuming the class that invokes everything is MainApp.java but it's in the package snews. The key is the word Main-Class: which will be used by the jar manifest.

Then, create the jar files including the manifest file:

   jar cmf mainFile snews.jar snews
(which creates a jar file named snews.jar from the package/directory snews and adds the file mainFile as part of the manifest).

You then invoke the program using

   java -jar snews.jar

I tested this, but you can type executable jar into google or your favorite search engine to find out more.


Owen L. Astrachan
Last modified: Sun Apr 29 22:53:12 EDT 2001