http://docs.oracle.com/javase/tutorial/deployment/jar/run.html
JAR Files as Applications
You can run JAR-packaged applications with the Java interpreter. The basic command is:
java -jar jar-file
The -jar flag tells the interpreter that the application is packaged in the JAR file format. You can only specify one JAR file, which must contain all the application-specific code.
Before you execute this command make sure the runtime environment has an information of which class within the JAR file is the application's entry point.
To indicate which class is the application's entry point, you must add a Main-Class header to the JAR file's manifest. The header takes the form:
Main-Class: classname
The header's value, classname , is the name of the class that's the application's entry point.
For more information, see the Setting an Application's Entry Point section.
When the Main-Class is set in the manifest file, you can run the application from the command line:
java -jar app.jar
To run the application from jar file that is in other directory, we need to specify the path of that directory as below: java -jar path/app.jar
where path
is the directory path at which this app.jar
resides.
An Example
We want to execute the main
method in the class MyClass
in the package MyPackage
when we run the JAR file.
We first create a text file named Manifest.txt
with the following contents:
Main-Class: MyPackage.MyClass
Warning:
The text 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.
We then create a JAR file named MyJar.jar
by entering the following command:
jar cfm MyJar.jar Manifest.txt MyPackage/*.class
This creates the JAR file with a manifest with the following contents:
Manifest-Version: 1.0 Created-By: 1.6.0 (Sun Microsystems Inc.) Main-Class: MyPackage.MyClass
When you run the JAR file with the following command, the main
method of MyClass
executes:
java -jar MyJar.jar
Setting an Entry Point with the JAR Tool
The 'e' flag (for 'entrypoint'), introduced in JDK 6, creates or overrides the manifest's Main-Class
attribute. It can be used while creating or updating a jar file. Use it to specify the application entry point without editing or creating the manifest file.
For example, this command creates app.jar
where the Main-Class
attribute value in the manifest is set to MyApp
:
jar cfe app.jar MyApp MyApp.class
You can directly invoke this application by running the following command:
java -jar app.jar
If the entrypoint class name is in a package it may use a '.' (dot) character as the delimiter. For example, if Main.class
is in a package called foo
the entry point can be specified in the following ways:
jar cfe Main.jar foo.Main foo/Main.class