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:
Operation | Command |
---|---|
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 run an application packaged as a JAR file (requires the Main-class manifest header) | java -jar app.jar |
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.
Here is an example manifest file for an application whose main class is formula.lexdriver:
Main-Class: formula.lexdriver
java -cp .:..:/home/bvz/cs365/formula.jar:/usr/local/lib/jar formula.lexdriver
You will of course need to replace my directory path with your own directory path.
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 formula.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.
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 formula.jar
You can find more information about jar files and manifest files at http://java.sun.com/docs/books/tutorial/jar.