Sunday, August 3, 2008

Making Executable JAR

As a Java programmer, you probably need to make JAR file, a compressed file which contains all necessary .class files, like tar (a widely used file format in Unix). For some reasons, you may want to make executable JAR file, which can run by "java -jar filename.jar" or just double click it on Windows. Here are the steps about how to make an executable JAR.

Suppose these are the source code:
src/com/wjb/goose.java
src/com/wjb/dog.java
src/com/wjb/zoo.java
Each source file contains only one class (except inner class) and belongs to the package "com.wjb".

For convenience, you'd better put the .class file into another directory, for example, classes. Here, directory classes and src are in the save level. The best way to do it is using "-d" argument. Open the terminal (or "command line prompt" on Windows), typing these commands:
cd src # Enter source code directory
javac -d ../classes com/wjb/goose.java
javac -d ../classes com/wjb/dog.java
javac -d ../classes com/wjb/zoo.java
-d ../classes means put the .class file into ../classes directory and build proper sub-directories according to the package name. For this example, it will make classes/com/wjb and all the class file will be put there.

Now suppose the Zoo class has the main method, i.e. it is the starting point of the whole programs. If you want to make executable JAR, you must specify the class that has the main method. So you need a special file: manifest.txt.

Create a text file named manifest.txt and save it in "classes" directory. This file has only one line:
Main-Class: com.wjb.Zoo
Note that there is a blank character after the colon ":" and you must use its full class name (containing package name).

Next, go to "classes" directory and execute this command:
jar -cmvf manifest.txt zoo.jar com
If everything is OK, the zoo.jar will be created. It is executable. You can use "java -jar zoo.jar" to test it or just double click its icon if you are using Windows.

In addition, the simple usage of "jar" to create a JAR file is:
jar -cmvf <manifest.txt> <filename.jar> <input files>

Here, "<input files>" are files or directories. You can specify more than one file or directory if you want to add many files into JAR. If you need the complete reference, please read the jar manual.

No comments: