Tuesday, November 2, 2010

How to create JAR

  • First, make sure you have installed Java 1.2 or above.
  • Next, create your working java files. In general, you will want to put it into a package. For this example, I created a trivial HelloWorld application that prints out "Hello World", and placed it into the package "hello". Therefore, the HelloWorld files (HelloWorld.class, HelloWorld.java) were located in the directory hello. I tested the system to make sure it worked before going on to the next step.
  • In the directory in which the hello is located, created a file called "mainClass". This file contains a single line specifying where the main Class is to be found in the jar file. Note that I use the package specification. Here is the single line:

Main-Class: hello.HelloWorld

 Note: make sure you type a carriage return after this line; some windows systems need it and will report a "Failed to load Main-Class manifest attribute" error.

 

  • Next, I create a jar file called hello.jar using the "jar" command in Java2. I use the "m" command line argument to specify the manifest file mainClass, which adds information to the jar file on where the main class will be found. Here is the jar command:

       pallava:~ > jar cmf mainClass hello.jar hello

    

  • Just for fun, and to check what's happened, I print the table of contents for the jar file I just created. Here's the command and its result:

      pallava:~ > jar tf hello.jar
      META-INF/
      META-INF/MANIFEST.MF
      hello/
      hello/HelloWorld.java
      hello/HelloWorld.class

 

  • Having successfully created the jar file, I can now invoke java2 on it with the command line argument:

      pallava:~ > java -jar hello.jar
      Hello World



One more example below

D:\>cd jr

D:\jr>cd j

D:\jr\j>javac HelloWorld.java

D:\jr\j>javac HelloWorld.java

D:\jr\j>cd ..

D:\jr>jar cmf mainClass j.jar j

D:\jr>jar tf j.jar

META-INF/

META-INF/MANIFEST.MF

j/

j/HelloWorld.java

j/HelloWorld.class

 

D:\jr>java -jar j.jar

Hello World!

D:\jr>