How to create JAR from Java Classes With Examples

Java Archive (JAR) files allows us to bundle multiple files in a single archive. Usually jar files contain class files and some other files like property files, images, applets etc.

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.

java-jar

  1. 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 bin directory. verbose option is added for debugging purpose only.
  2. Using jar command to create the jar archive.

    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.

By admin

Leave a Reply

%d bloggers like this: