Running an executable JAR from command-line

An “executable JAR” is nothing but a JAR in which the entry point of execution is defined. That definition can be given in its manifest file (META-INF/Manifest.mf).

The general structure of a JAR file:

+-MyJar.jar
|-+-META-INF
|-|----Manifest.mf
|-+-com
|-|-+-package
|-|-|----MyJavaFile.java
|-|-|----MySecondJavaFile.java

The manifest file should contain the details of the JAR file. It keeps the attribute as key-value pairs.

The structure of a manifest file:

Main-Class: com.package.MyJavaFile
Specification-Title: "My Classes"
Specification-Version:
"1.0"
Specification-Vendor: "Sun Microsystems, Inc."
Implementation-Title:
"subin.util"
Implementation-Version: "build01"
Implementation-Vendor: "Sun Microsystems, Inc."

If the executable JAR is dependent on any other JAR, we need to specify it in the Manifest itself (even though there is an option to do it while invoking the application thru java -cp).

Class-Path: aJar.jar anotherJar.jar

I had some problems in building a JAR file using the conventional jar -cvf command. Whatever I do, it was not picking my custom manifest (I’m very bad). So, I used ANT to build a JAR.

ANT file to build a JAR:

<project name="Demo" default="build.jar.file">
  <target name="build.jar.file">
    <jar destfile="myJar.jar" basedir=".">
      <manifest>
        <attribute name="Main-Class" value="com.package.MyJavaFile" />
        <attribute name="Class-Path" value="aJar.jar anotherJar.jar" />
      </manifest>
    </jar>
    <copyfile dest="/path/to/deploy" src="myJar.jar"/>
  </target>
</project>
  • use ANT or Eclipse IDE to build the JAR

Running the JAR from the command-line:

$ java -jar myJar.jar [optional parameters]

External Links:
http://en.wikipedia.org/wiki/Manifest_file
http://en.wikipedia.org/wiki/JAR_file
http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html
http://java.sun.com/docs/books/tutorial/deployment/jar/ – Packaging tutorial from Sun
http://ant.apache.org/manual/
http://en.wikipedia.org/wiki/Apache_Ant

About these ads