Tuesday, April 27, 2010

How to create a jar file from several existing files

The basic format of the command for creating a JAR file is:

jar cf file-name (all input-file)


The c option indicates that you want to create a JAR file.The f option indicates that you want the output to go to a file rather than to stdout.The c and f options can appear in either order, but there must not be any space between them.

file-name is the name that you want the resulting JAR file to have. By convention, we use a .jar extension for jar files.

The (all input-file) argument is a space-separated list of one or more files that you want to include in your JAR file. (all input-file) argument can contain the wildcard * symbol which means include all the files in that directory. If any of the input-files are directories, the contents of those directories are added to the JAR thus created.

I will give an example to illustrate this.

I have a folder which contains two class files

HumanTaskTest.class and HumanTaskTestBean.class

Nnow we will see how to jar it.

Open a command prompt and navigate till the directory where in you have stored your class files



Now use the following command

>jar cf HumanTask *

It will create a jar file with name HumanTask and will contain all the file in that folder.

But we recommend to use the .jar extension while creating a .jar file

also instead of * you can use the individual file name as

jar cf HumanTask.jar HumanTaskTest.class HumanTaskTestBean.class


It will contain a file HumanTask.jar and will include the two class files




we have further more options like using jar command options

like if you use following command

jar cvf human.jar *

It will again create a .jar file which will produce verbose output on your console as



Now one interesting thing.

Try to extract this .jar file now created.

It will produce the two class file and one more folder which we have not defined any where it will be bydefault META-INF folder.

If you will open this you will get a file called MANIFEST.MF

When you extract a jar file , it automatically creates a default manifest file. There can be only one manifest file in an archive, and it should always have the pathname as META-INF/MANIFEST.MF

It contains the following information

Manifest-Version: 1.0
Created-By: 1.6.0 (Sun Microsystems Inc.)


It can contain information about other files that are packaged in the archive.

So knowing bit about the manifest file we have following command options


v -It Produces verbose output on stdout while the JAR file is being built. The verbose output tells you the name of each file as it's added to the JAR file.we have already seen an example.

M -It says that the default manifest file should not be produced.

m - It is used to include manifest information from an existing manifest file. The format for using this option is:

jar cmf "existing manifest file" "jar file" "input files"

No comments: