Pre-requisites:
JRE(any version above 1.2)
JDK (any version above 1.2)
This article demonstrates the creation of an executable jar file. This is a hands-on tutorial, I recommend you to follow the below mentioned steps practically instead of simply reading this tutorial.
Step 1:
Download Source Code (nodalo-src.zip) and Binary Classes (nodalo-bin.zip) of the sample Java Project used in this post. Extract the downloaded archive nodalo-bin.zip to Windows D: Drive (D drive optional, can be extracted to any folder).
The structure of the folder ‘nodalo-bin’ would look like this:
nodalo-bin
|___com
|__A.class
|__B.class
|__C.class
|___foo
|__D.class
There is a root directory ‘nodalo-bin’, which in turn has two directories ‘com’ and ‘foo’. Package com contains classes A.class, B.class, C.class . Package foo contains class D.class .
Class B.class has the main method. Our aim is to create an executable jar file, name it nodalo.jar and run main method in the Java Class B.
Step 2:
Create a jar file nodalo.jar that has the directories com and foo in it.
Browse to the directory named “nodalo-bin” and execute the following command in Command Prompt or Terminal.
D:\nodalo-bin> jar cvf nodalo.jar com foo
This command would create nodalo.jar
To view the contents of this jar file, execute:
D:\nodalo-bin>jar tf nodalo.jar
The following output would be shown:
META-INF/MANIFEST.MF com/ com/A.class com/B.class com/C.class foo/ foo/D.class
Note that META-INF folder and the file MANIFEST.MF were created on their own.
Step 3:
To execute this jar file, run command:
D:\nodalo-bin>java -jar nodalo.jar
An error similar to the one below would result in the output:
Failed to load Main-Class manifest attribute from nodalo.jar
Step 4:
This is because java does not know where to look for the main method. So we need to explicitly add a manifest file that tells JVM about the Class that contains main method in this Java project.
Create a new text file, name it mainClass.txt and put the following line of code in it:
Main-Class: com.B
Save mainClass.txt in the nodalo-bin directory. The above line instructs JVM to look for main method in B.class
To merge this Manifest file with the one already existing in nodalo.jar, execute the command:
D:\nodalo-bin> jar cmf mainClass.txt nodalo.jar com foo
Now, try executing the jar again:
D:\nodalo-bin>java -jar nodalo.jar
The above command should result in output:
Inside Class D Inside Class C Inside Class B Inside Class A
Great! We have successfully created an executable jar file. Please comment below, if this tutorial helped you.
Read more about Manifest File in Java.