Real'sHowTo AddThis Feed Button
Custom Search

Make a JAR executableTag(s): Environment


In the manifest file of a JAR, it is possible to specify the class to be used when the JVM is lauched with the JAR as parameter. The class must have a main().

Try with this simple class

import java.awt.*;
import java.awt.event.*;

public class MyClass {
 public static void main(String[] args) {
    Frame f = new Frame();
    f.addWindowListener
          (new WindowAdapter() {
              public void windowClosing(WindowEvent e) {
                 System.exit(0);
                 }
              }
    );
    f.add(new Label("Hello world"));
    f.setSize(200,200);
    f.setVisible(true);
 }
}
Then create this manifest file (manifest.mft) with any text editor.
Manifest-Version: 1.0
Main-Class: MyClass
Class-path: .
Main-Class specifies the entry point with the main(String args[]) method.

The Class-path is used to specify the dependency of this jar (if any). You add the directories and jars separated by a space. It is important because when running a jar , the CLASSPATH definition (as defined by the environnement variable) is overridden.

Next, you include the manifest file in the JAR (MyJar.jar) with the MyClass class.

jar cvfm myjar.jar manifest.mft *.class
Then you are able to start the MyClass.class by double-clicking on the MyJar.jar file (if the JRE is correctly installed) or by typing
java -jar myjar.jar
If you need to pass parameters, use the -D switch before the -jar switch and use the getProperty() method to get the value.
The file association mechanism is made during the installation of the JRE.

You can verify that everything is ok with the following command from a DOS Shell

>assoc .jar
.jar=jarfile

>ftype jarfile
jarfile="C:\Program Files\Java\jre1.5.0_10\bin\javaw.exe" -jar "%1" %*

If the association is broken or you need to change the JRE used then by using the assoc/ftype utilities, you can modify the association easily (use /? to display the syntax of the assoc and ftype utilities).

NOTE: On WinXp (or better), your user account needs to be at the Admin level.


On Windows (NT or better), you can also make JARs run from the command-line by setting the PATHEXT environment variable, for example

SET PATHEXT=.EXE;.BAT;.CMD;.JAR
Then if you have the jar file MyJar.jar accessible via the PATH environment variable, typing "MyJar" on the DOS command line will invoke "javaw -jar MyJar.jar" .
blog comments powered by Disqus


If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2014
[ home ]