Running a 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:
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:> jikes 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.
Get Java Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.