Java - Core Java - Need of jar

Need of jar in Java

Jar stands for Java Archive. It is a java based compressed file and used for grouping java library files (i.e. class files) for distributing library file as part of software.

How can we create a java achieve file by using jar command?

Ans: jar command has different options to create and use jar file.

To know more jar options:

  • open command prompt
  • type jar and press enter key on keyboard
  • you will find the usage of jar command with various options
  • The important options are
  • -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 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
  • If any file is a directory then it is processed recursively.

    The manifest file name, the archive file name and the entry point name are specified in the same order as the 'm', 'f' and 'e' flags.

    Example 1:

    to archive two class files into an archive called classes.jar: jar cvf classes.jar Foo.class Bar.class

    Example 2:

    use an existing manifest file 'mymanifest' and archive all the files in the foo/ directory into 'classes.jar':

     jar cvfm classes.jar mymanifest -C foo/ .

    Syntax to create jar file

    Open command prompt -> change directory path to present working directory and run following command

    1567172847-image.png For Example:
    jar -cvf javafile.jar abc xyz mbc.txt
    only abc, xyz and mbc.txt file are added to jar file from present working directory and jar file is stored in the same present working directory
    jar -cvf javafile.jar
    All files and folder of the present working directory are added.
    jar -cvf test.jar *.txt
    only .txt extinction file are added to jar file.

    The above jar file is a normal jar file, not an executable jar file.


    To create chating.jar file having clients class as main class use following command

    jar cvfe chating.jar client clients.class servers.class index.jpg