We all have used jar files in projects, even JRE classes are packed as jar (rt.jar or classes.jar).
We can create jar file from any file, it’s similar to zip file.
Here we will learn how to create a jar file from a java project. I have two packages and two classes in my java project (MyProject). The project structure looks like below image.
- Compile the java classes. This step is optional if classes are already compiled and inside target directory.
Note that I am compiling both the packages classes in
bindirectory. verbose option is added for debugging purpose only.
jarcommand to create the jar archive.
1234567891011pankaj@JD:~/CODE/MyProject/src$ cd ../binpankaj@JD:~/CODE/MyProject/bin$ jar cvf MyProject.jar *added manifestadding: com/(in = 0) (out= 0)(stored 0%)adding: com/journaldev/(in = 0) (out= 0)(stored 0%)adding: com/journaldev/test/(in = 0) (out= 0)(stored 0%)adding: com/journaldev/test/MyTest.class(in = 444) (out= 303)(deflated 31%)adding: com/journaldev/util/(in = 0) (out= 0)(stored 0%)adding: com/journaldev/util/MyUtil.class(in = 444) (out= 304)(deflated 31%)
Option c indicates that we want to create the jar file. Option v runs the jar command in verbose option that prints all the files included in jar archive and compression details. Option f allows us to send the output to the given file name.
Notice that jar command automatically adds the manifest file in the jar. Manifest file contains the metadata of jar file and it’s stored in META-INF/MANIFEST.MF file.
We can add our own manifest file with command
jar cvmf MANIFEST.MF MyProject.jar com.
jar command matches the input parameters with the option name. Since we are using option as cvmf, we need to give the manifest file name first and then the jar file name.
Your jar file is ready and you can use it in any other projects.