JAR Files

A JAR file is similar to a tar file in that it constitutes an archive of Java class files. JAR files are created with the jar command and the jar command takes many of the same arguments as tar. The jar command automatically performs compression on your class files using the ZIP file format.

You can use the jar command to package all the class files for your application into a single file. If you also tell the jar command the main class to access within the jar file, then you can treat the jar file as a pseudo-object file.

The following table, which I copied from Sun's tutorial website on the jar command, shows the most common uses of the jar command:

OperationCommand
To create a JAR file jar cf jar-file input-file(s)
To view the contents of a JAR file jar tf jar-file
To extract the contents of a JAR file jar xf jar-file
To extract specific files from a JAR file jar xf jar-file archived-file(s)
To run an application packaged as a JAR file (requires the Main-class manifest header)
java -jar app.jar
To invoke an applet packaged as a JAR file
<applet code=AppletClassName.class
        archive="JarFileName.jar"
        width=width height=height>
</applet>

Specifying an Application's Entry Point

You can tell java how to find the entry point within your jar file by creating a manifest file. A manifest file can have any name you choose although manifest.txt is a commonly chosen one. A manifest file should contain the following single statement:

Main-Class: classname

Main-Class is a required keyword and classname is the name of the class that contains your application's main method. The Sun tutorial website also includes the following warning:

The manifest file must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.

Here is an example manifest file for an application whose main class is ExpressionTree:

Main-Class: ExpressionTree

Creating a Jar File that Contains a Manifest

When you create your jar file, you will must include m as a command line option. This option causes java to use the file specified after the m flag as the manifest file. For example, if the above file is named manifest.txt and your files are in a directory named formula, you could create your jar file with the following command:

jar cmf manifest.txt ExpressionTree.jar formula

Note that you can specify all of your flags before specifying the files. The files should be specified in the same order as the flags. The name of the jar file does not have to be the same as your main class.

Executing a Jar File with an Application Entry Point

In order to execute a jar file that has an entry point specified, invoke java with the -jar option and the jar file's name. For example:

java -jar ExpressionTree.jar


Where to Find More Information about Jar Files

You can find more information about jar files and manifest files at http://java.sun.com/docs/books/tutorial/jar.