Saturday, August 1, 2009

Java Archive File



Creating an executable jar file:

JAR stands for Java Archive File. A jar file is used to hold a collection of class files packaged together in a compressed format. A jar file is similar to a zip file. To create a jar file, you need to install Java SE Development Kit (JDK). If you are able to execute a java source files in your system then you are set to go. In this tutorial, you will learn how to create an executable jar file.


First thing you need is a Java source file. A simple program that just gets and sends data to the command prompt will work as long as you run it from the command-line, but you will not be able to see any output if you just double click on the Jar file. So, in this tutorial I will use an example that creates a window using an Applet.Step 1. Create a folder called sample and put all your Java sources that you want to add t you jar file. For my example I’ve created a simple gaming application which generates the score of each player in a randomized manner, lol.






Step 2. Create a manifest file… I have created Cricket.MF. A manifest is basically a file that contains information about the files packaged inside the Jar file. You can create yours using a text editor with .MF extension. Type the below code in the Manifest file.
Code:
Manifest-Version: 1.0


Main-Class: cricket1


Created-By: 1.2 (Sun Microsystems Inc.)

The first line tells us that this file corresponds to 1.0 of the manifest specification. As the name indicates, the Main-Class attribute specifies the class file that hold the main function. And the last line defines the version and the vendor of the java implementation on top of which this manifest file is generated.Step 3: Jar command is used to create the Jar file. In the example below (jar) is the name of the executable you call to create the Jar file. The jar command has a number of options…I used four of them (c –create the jar file, v –generates verbose output to the screen during file creation, f –specifies the file to be created, and m –indicates the manifest file to be used) After the options parameter comes the name of the jar file to be created (Crick.jar), followed by the name of the manifest file to use (Cricket.MF). The (*) wild card indicates to include all files in that directory. If you wanted you could use *.class to only include class files. Here's the command:


Code:
jar cvfm Crick.jar Cricket.MF *


Your source folder should now contain java source files, class files, Manifest file and the jar file.




You should be able to double click on the Crick.jar, and it will execute. To execute the code from the command line, type the following code

java -jar Crick.jar




Post your queries if any.
You are visitor no.