Let’s say you created a standalone java application and you want to execute it as a jar file.
You want to run the main method of a particular class in your application when the jar file is executed.
This post explains the steps to convert a java application to a jar file using command line.
I created a simple HelloWorld application which has a single class named HelloWorld.java under the package helloworld which prints the text Hello World! to the console.
Here is the structure:
On building the project the class files got generated in bin folder like below:
Now when you create a jar file by default java generates a manifest file (MANIFEST.MF) under META-INF folder.
This file contains meta information about the application . By default it contains Manifest-Version and Created-By fields in name:value pair format.
When you create a jar file you need to tell Java which is the main class whose main method should be run by JVM.
This can be done by creating a new file and telling java to add the information in the file to the manifest file already created.
STEP 1: Create the manifest file
Go to the bin folder where the class files got generated
Let’s first create the manifest file , I have named it manifest.txt and placed it in bin folder :
Add the name of the main class next to Main-Class keyname like below in the manifest file:
Notice that the name starts with the package name followed by dot followed by the class name with no extension.
Also notice the cursor in the next line (you should enter a newline character – by pressing ENTER key ). This is needed for java to recognize the file.
STEP 2: Run jar command
Run jar command by specifying few parameters.
Here is the jar command :
jar cfm helloworld.jar manifest.txt helloworld
c means you are going to CREATE a jar
f means you are going to create a FILE(jar file)
m means you are going to modify existing manifest file using the information in the supplied file
In our case we are going to tell Java which is the main class it should run .
next to the above arguments mention the jar file name (.jar is optional)
this is followed by the manifest.txt file which contains the addition to MANIFEST.MF file
And that is followed by the package name which contains the java classes (if there is more than one package name you can specify them separated by spaces). Also you can use wildcards (* takes all the packages and files from the current working directory) .
Once run the jar file gets generated in bin folder:
STEP 3: Verify
Execute the jar file using the below command:
java -jar helloworld.jar
Hello World got printed!
You can ignore the manifest file if you just want to create a java library and not a java application that needs to be executed.
In that case the below command would suffice:
jar cf helloworld.jar helloworld
This generates the jar file helloworld.jar which can be used as a library in other projects.
Leave a Reply