Create JAR Files in Java

Console or command prompt is used to create JAR files.

Command for creating JAR

jar cf jar-file-name.jar File(s)_to_add

where,

  • jar indicates to call the jar tool.
  • c indicates to create.
  • f indicates a jar should be output in file rather than in console.
  • jar-file-name indicates the name of jar file that should be created.
  • File(s)_to_add indicates the files that should be added to the jar file. Each file is separated with a space.

Example

jar cf myJar.jar Music.class Equalizer.class song.mp3

Output

A JAR file is created in the current folder with Music.class, Equalizer.class, song.mp3 and a default MANIFEST.MF File which contains information about jar files inside a directory META-INF.


Other commands

  • v indicates verbose output i.e print details in console.

    Example

    jar cvf myJar.jar Music.class Equalizer.class song.mp3

    Output

    added manifest

    adding: Music.class(in = 699) (out= 411)(deflated 41%)

    adding: Equalizer.class(in = 287) (out= 226)(deflated 21%)

    adding: song.mp3(in = 6990) (out= 4110)(deflated 41%)

    where,

    (in=699) indicates input file size

    (out= 411) indicates output file size

    (deflated 41%) indicates compression rate

  • 0 indicates to avoid compression.

    Example

    jar cv0f myJar.jar Music.class Equalizer.class song.mp3

    Output

    added manifest

    adding: Music.class(in = 699) (out= 699)(stored 0%)

    adding: Equalizer.class(in = 287) (out= 287)(stored 0%)

    adding: song.mp3(in = 6990) (out= 6990)(stored 0%)

  • M indicates not to produce default Manifest File.

    Example

    jar cv0Mf myJar.jar Music.class Equalizer.class song.mp3

    Output

    adding: Music.class(in = 699) (out= 699)(stored 0%)

    adding: Equalizer.class(in = 287) (out= 287)(stored 0%)

    adding: song.mp3(in = 6990) (out= 6990)(stored 0%)

  • -C indicates change the directory during execution of command.

    We can use this when a file is present in directory other than root directory.

    Assume song.mp3 is present inside audio directory

    Example

    jar cv0Mf myJar.jar Music.class Equalizer.class -C audio song.mp3

    Output

    adding: Music.class(in = 699) (out= 699)(stored 0%)

    adding: Equalizer.class(in = 287) (out= 287)(stored 0%)

    adding: song.mp3(in = 6990) (out= 6990)(stored 0%)

  • m indicates to include external manifest file instead of default manifest.

    Example

    jar cv0Mfm myJar.jar your_manifest.txt Music.class Equalizer.class song.mp3

    Output

    adding: Music.class(in = 699) (out= 699)(stored 0%)

    adding: Equalizer.class(in = 287) (out= 287)(stored 0%)

    adding: song.mp3(in = 6990) (out= 6990)(stored 0%)

    If you want to learn about external manifest file, signing JAR and package sealing in depth, you can refer the official Java documentation by Oracle.