In this tutorials, we are going to learn about what is a jar file and how to create and extract.

Jar File :

A jar file represents a group of .class files. In Java if we need to work with several dependent classes it is not recommended to set class path for every individual class.

We have to group all those .class files into a single unit called jar and then it will be set to class path.

Examples for jar Files :

  1. To develop a servlet based applications, all servlet dependent classes are available in servlet-api.jar, hence to compile a servlet program we have to place servlet-api.jar in class path.
  2. To use Log4J in our application all dependent classes are available in log4j.jar.

How to create Jar file :

We can create jar file by passing the below commands on your command prompt.

syntax :

[box type=”shadow” align=”alignleft” class=”” width=”100%”]

jar   -<options>   jar_file_name   path(.class files location)

[/box]

Example :

Usually we can create a jar using below commands.

[box type=”shadow” align=”alignleft” class=”” width=”100%”]

jar   -cvf   sample.jar   Test.class   Test2.class   Test3.class

jar   -cvf   sample2.jar   C:\Java\classes\*.class

[/box]

Extract a jar File :

We can exact a jar file using the below command.

[box type=”shadow” align=”alignleft” class=”” width=”100%”]

jar   -xvf   sample.jar

[/box]

Display the content of a jar :

We can see the content of the jar with out extracting it by using the below command.

[box type=”shadow” align=”alignleft” class=”” width=”100%”]

jar   -tvf   sample.jar

[/box]

Options :

Below are the all possible options to create a jar.
[tie_list type=”checklist”]

  •    -c  create new archive
  •    -t  list table of contents for archive
  •     -x  extract named (or all) files from archive
  •     -u  update existing archive
  •     -v  generate verbose output on standard output
  •     -f  specify archive file name
  •     -m  include manifest information from specified manifest file
  •     -n  perform Pack200 normalization after creating a new archive
  •     -e  specify application entry point for stand-alone application bundled into an executable jar file
  •     -0  store only; use no ZIP compression
  •     -P  preserve leading ‘/’ (absolute path) and “..” (parent directory) components from file names
  •     -M  do not create a manifest file for the entries
  •     -i  generate index information for the specified jar files
  •     -C  change to the specified directory and include the following file

[/tie_list]

Happy Learning 🙂