Tuesday 8 April 2014

CREATE AN EXECUTABLE JAR FILE



In Java, it is common to combine several classes in one .jar (" java archive ") file.  Library classes are stored that way and larger projects also use jar files.  You can create your own jar file combining several classes. 

jar files are created using the jar.exe utility program from JDK.  You can make your jar file runnable by telling jar.exe which class has main.  To do that, you need to create a manifest file.  A manifest is a one-line text file with a "Main-Class" directive.  For example:
Main-Class: Main
This line must end with a newline. 

A jar file created with a main class manifest can be used both as a library and a runnable jar.  If you use it as a library, you can edit and compile any of the classes included in the jar, and add it to your project.  Then it will override the one in the jar file. 

You can create a manifest file in any text editor, or even by using the MS-DOS echo command.  You can give your manifest file any name, but it's better to use something standard, such as manifest.mf  

Once you have a manifest and all your classes have been compiled, you need to run JDK's jar.exe utility.  It is located in the JDK’s bin folder, the same place where javac.exe and java.exe are.  jar.exe takes command-line arguments; if you run it without any arguments, it will display the usage information and examples.  You need
C:\mywork> jar cvfm MyJarName.jar manifest.txt *.class
cvfm means "create a jar; show verbose output (verbose is for displaying the work done by JVM); specify the output jar file name; specify the manifest file name."  This is followed by the name you wish to give to your jar file, the name of your manifest file, and the list of .class files that you want included in the jar.  *.class means all class files in the current directory.

Actually, if your manifest contains only the Main-Class directive, you can specify the main class directly on the jar.exe's command line, using the e switch, instead of m.  Then you do not need a separate manifest file; jar will add the required manifest to your jar file for you. For example:
C\mywork> jar cvfe MyJarName.jar MyMainClass *.class

No comments:

Post a Comment