Monday, June 28, 2010

Creating and Executing a Jar file using Command Prompt in Java

Dear reader,

I am writing an article today about creation and execution of Jar file in Java.
A jar file is nothing but a zipped file having Java classes and other files (may be xml, properties, manifest file etc).

Creation of Jar is quite easier however sometimes we face problem while executing a jar which has a main class
and if that requires some supporting Jar files too. By the way, if you know these things, you can ignore this 
article. But I do hope, please go through once and comment if find something better..

//Creating Jar and Running Jar file from Command Prompt
1) First Test your program without creating jar file, whether it is running or not.
//For this, first set classpath in Windows Operating System, we assume our package starts from "D:\smpp_new>" directory:
Directory structure:  D:\smpp_new>com\......\*.java

    Command_Prompt> set classpath=;%classpath%;.

//Compiling and creating packages with Classes in one command
    D:\smpp_new>javac -d . com\logica\smpp\test\SMPPConnector.java

//Running your main class, We assume Main class is "SMPPConnector.java" which is in below package
    D:\smpp_new>java com/logica/smpp/test/SMPPConnector


//If it runs, then fine.....we will go ahead creating JAR and running it....

2) Now create a Folder in parallel to your Starting package.. here in "D:\smpp_new>" as "META-INF". Then create a file "MANIFEST.MF" inside this META-INF folder, now your directory structure will be:
E.g:  D:\smpp_new>com\......\*.java
    D:\smpp_new>META-INF\MANIFEST.MF

//Contents of MANIFEST.MF file:
    Manifest-Version: 1.2
    Main-Class: com.logica.smpp.test.SMPPConnector
    Created-By: 1.5 (Sun Microsystems Inc.)

    //Remember, after writing this, your cursor should be at the end of the line "Created-By: 1.5 (Sun Microsystems Inc.)", 
    //Not below this line. Manifest jar should not have "/n" type of things.

    //In case your jar is dependent on some classpath, which still needs at runtime, please mention it in MANIFEST FILE like below:
    Manifest-Version: 1.2
    Class-Path: ./DecryptionUtilityLib/commons-codec-1.3.jar ./DecryptionUtilityLib/coreUtil.jar
    Created-By: 1.5 (Sun Microsystems Inc.)
    Main-Class: com.ewp.services.DecryptData

//Now create Jar file:
    D:\smpp_new>jar cfm smppconnector.jar META-INF\MANIFEST.MF com\*

//Run your Jar file:
    D:\smpp_new>java -jar smppconnector.jar

No comments:

Post a Comment