Creating A Jar Archive
Posted Apr 27th, 2009 by Conor in in Java,LanguagesI made the HelloWorld class a few days ago in this post. I am getting a bit ahead of myself here but what if you have an application with many files? Do you let the user handle all those files yourself? No! The Java Archiving Format .jar is the solution. With it you can create an entire application and bring it down to one file. Then you can run the whole application from that file! This can be done with the option of compression aswell.
Anyway even though it seems useless to create a jar archive of one file I am going to create one for the HelloWorld.class. First I need to create a file in which to store the manifest. This file will contain crucial information about the application and how it is run. I am going to do the bare minimum at the moment but there are endless possibilities with this file! This is what I put in HelloWorld.mf:
Main-Class: HelloWorld Name: class/ Sealed: true
The main class tells the application which class to load first. Name and sealed tell the application which folders to seal. You might want to seal a package to ensure version consistency among the classes in your software.
I now have two files; HelloWorld.class and HelloWorld.MF. Now I must compress them both into a jar archive and run the application. To create the jar archive execute:
jar cmf HelloWorld.mf HelloWorld.jar HelloWorld.class
Basically this says create a new jar archive including the manifest and the class file and locate it in a new file called HelloWorld.jar. Now the application is executable. To run it simply type:
java -jar HelloWorld.jar
You should see the same output from the original application:
[conor@host java]$ java -jar HelloWorld.jar Hello World!
Simple as that!