Thursday, May 13, 2010

Jar file Vs Executable Jar file

Jar file is the combination of compiled java classes.
Executable jar file is also be combination of compiled java classes with Main class.
Normal jar file can be created as
C:\> jar -cvf TestNew.jar . 
But while creating executable jar file we have to specify the Main-Class in a manifest file. Following are the steps to fallow while creating the executable jar file. Here its explained with a simple class in a test package.
Step1: create a java class TestNew under package test
package test;
public class TestNew{
public static void main(String a[]){
System.out.println("Hello world");
Step 2: compile the class with fallowing command
C:\>javac -d . 
Note: Once you run the TestNew class you have to get “HelloWorld” in the console. To run use fallowing command
C:\>java test.TestNew
Step 3: Create a “mainClass” file in the directory where your test folder is located . 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: test.TestNew
Note: specify the single line only don't specify anything
Step 4: create the jar using fallowing command
C:\>jar cmf mainClass test.jar test
Where “c” represents the create that you are going to “create”, "m" specifies the manifest file mainClass (which adds information to the jar file on where the main class will be found) and “f ” refers to “file”.
Note: The file has to be created in your folder with the name test.jar

To view the content of the jar file you can use the fallowing command
C:\>jar tf test.jar
It displays as:
To execute the jar file you can use the following commond
C:\>java -jar test.jar
Hello world

No comments: