Recipe 23.7 Running a Main Program from a JAR


Problem

You want to distribute a single large file containing all the classes of your application and run the main program from within the JAR.

Solution

Create a JAR file with a Main-Class: line in the manifest; run the program with the java -jar option.

Discussion

The java command has a -jar option that tells it to run the main program found within a JAR file. In this case, it will also find classes it needs to load from within the same JAR file. How does it know which class to run? You must tell it. Create a one-line entry like this, noting that the attribute fields are case-sensitive and that the colon must be followed by a space:

Main-Class: HelloWorld

in a file called, say, manifest.stub, and assuming that you want to run the program HelloWorld . Then give the following commands:

C:> javac HelloWorld.java C:> jar cvmf manifest.stub hello.jar HelloWorld.class C:> java -jar hello.jar Hello, World of Java C:>

You can now copy the JAR file anywhere and run it the same way. You do not need to add it to your CLASSPATH or list the name of the main class.

On GUI platforms that support it, you can also launch this application by double-clicking on the JAR file. This works at least on Mac OS X and on Windows with the Sun Java runtime installed.

23.7.4 Mac OS X Specifics

On Mac OS X, you can use the Jar Bundler (under /Developer/Applications/Java Tools/Jar Bundler.app). This provides a windowed tool to specify the options set by my MacOSUI package (see Recipe Recipe 14.16) as well as CLASSPATH and other attributes. See Figure 23-5.

Figure 23-5. Mac OS Jar Bundler (OS X 10.3.2 version)
figs/jcb2_2305.gif




Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net