Java Workshop
 

Java Archive (Jar) Files

Jargon

Algorithm
A step-by-step problem-solving procedure, especially an established, recursive computational procedure for solving a problem in a finite number of steps.
Archive
A file that contains a group of files and possibly directories which must be extracted in order to use them. An archive may optionally be compressed which would require it to be decompressed before the files can be extracted.
Compression
The temporary coding of data in a way that saves storage space or transmission time. Most text files can be compressed to about half their normal size. Graphics can be compressed to 10 percent of their original size.
Digital Signing
An attempt to mimic the offline act of a person applying their signature to a paper document.
Enumeration
An object that assists in iterating over a set of objects.
Portability
A measure of system independence; portable programs can be moved to a new system by recompiling without having to make any other changes.
Sealed
A Sealed Jar guarantees that all classes in a package come from the same code source.
Security
Techniques and practices that preserve the integrity of computer systems, and digital library services and collections.
Stream
A continuous flow of data, usually digitally encoded, designed to be processed sequentially. Also called a bitstream.
Versioning
Versioning is a mechanism that keeps track of all changes in content and code and allows any change to be 'rolled back' to any previous version. This also means that a deleted file can be recovered to its last saved state.

Introduction

Jar files provide a way to package software written in Java and to easily distribute that software. In this chapter we will look at what Jar files are, how to use them and how to use the Jar API to access Jar files directly from within our programs.

What Are Jar Files?

A Compressed Java Archive File

A Java Archive File, commonly referred to as a Jar File is nothing more than a compressed archive file. The file has two important characteristics:

  • The archive does not have to be compressed but if it is, the Zip compression algorithm is used.
  • The archive's filename must have the .jar extension.

Archives are used to bundle a number of files and directories into one single file, as such Java Archives or Jar Files are no different. Typically, Jar files are used to distribute Java software, these Jar files contains the actual class files of the programs archived in them.

Some benefits of using Jar files are:

  • Security, A jar file can be digitally signed enabling users to verify the signature and then grant the program security privileges.
  • Decreased download time, since the archive is compressed it takes less time to download than it would to download each individual file.
  • Package Versioning, A Jar file may contain vendor and version information about the files it contains.
  • Portability, all Java Runtime Environments know how to handle Jar files.

Creating and Viewing a Jar File

The Jar Tool comes bundled with the Java Development Kit, so if you have a JDK installed you will have the Jar tool. The Jar tool is run via the command line, this means you will use an MS Dos Prompt in Windows and a Shell or Console in Linux / Unix. The command for running the Jar tool is jar, you simply issue this command in the command line.

The basic command for creating a Jar file is:

jar cf jar-filename   input-files
                

The c option indicates that you wish to create a jar and the f option indicates that output should be sent to a file, jar-filename is the name of the resulting Jar file and input-files are the files you wish to include.

As an example, consider a program in the project directory. The program consists of a class file and some images in an images directory:

example

You would then run the following command to create the jar file from within the project directory.

jar cvf project.jar MyClass.class images
                

The v option is for verbose output. The output would be as follows:

added manifest
adding: MyClass.class(in = 462) (out= 291)(deflated 37%)
adding: images/(in = 0) (out= 0)(stored 0%)
adding: images/logo.gif(in = 4178) (out= 4001)(deflated 4%)
                

The command to view the contents of a jar file is as follows:

jar tf jar-filename
                

The t option is to print a table of contents and the f option indicates that your are reading from a file, the jar-filename is the filename of the jar you wish to use. If we use the jar file we created earlier:

jar tf project.jar                
                

The output is as follows:

META-INF/
META-INF/MANIFEST.MF
MyClass.class
images/
images/logo.gif
                

The output indicates that out class file and the images directory were included in the jar file. You will also notice that the Jar tool, automatically created and added the manifest file for us. We will find out more about this file in the next section.

Extracting Files from a Jar File

If we wish to extract a file from the Jar file, we use the following command:

jar xf jar-filename  archived-files
                

The x option indicates we wish to extract files, the f option indicates from a jar file, the jar-filename is the filename of the jar file to extract from and the archived-files are the files to extract. In our example we can do the following:

jar xf project.jar MyClass.class images/logo.gif
            

This will produce no output on the command line, but will extract the class file and the image file. We can also extract all files by simply not specifying which files to extract:

jar xf project.jar
            

If you look in the project directory you will notice a directory named META-INF which contains a file named MANIFEST.MF.

Packaging Software in a Jar File

The Manifest File

We said earlier that the Jar file automatically adds a manifest file to the jar file, the file is always in a directory named META-INF and is named MANIFEST.MF; these are, like Java, case sensitive. This file contins information about the jar file and the files it contains. If you open the manifest file that was extracted in the previous section you will see it contains the following:

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

Jar files are used in a wide variety of situations and therefore need to support a wide range of functionality like digital signing, version control, package sealing, and others. By tailoring the meta information contained in the manifest file, this Jar file is enabled to be used in these situations.

An example of modifying the manifest file is package sealing, which means that all classes defined in a package must be archived in the same Jar file. To do this you need to add a Name and Sealed header to the manifest file, the name contains the package name and the sealed header indicates whether it is sealed or not.

Name: MyCompany/MyProject/MyPackage/
Sealed: true
                

You would add this information to a text file, suppose it is named seal.txt, you can add this information to the manifest using the m option.

jar cmf seal.txt myJar.jar MyCompany
                

Two other important manifest headers are the Main-Class and Class-Path, which are used to bundle software into a Jar file so that the software can be run from within the Jar file. This is known as an executable Jar file.

Packaging the Program

Assume your program is name Main.java which compiles to Main.class, and that it requires a jar file named jutil.jar in the lib directory. You can get the source code here. You will then add the following to a text file named headers.txt:

Main-Class: Main
Class-Path: ./lib/jutil.jar
                

Make sure the headers.txt has a blank new line at the end of it. You can use the following command to create the Jar file.

jar cmf headers.txt project.jar Main.class
                

Running the Program

You will use the Java tool to run the program packaged inside the Jar file. Simply issue the command:

java -jar project.jar
                

This should run the program which will display a blank Swing Window.

Swing Window

Using The Jar API

Java comes with an API for working with Zip archives as well as Jar files. In this section we'll look at how to use these APIs.

Printing the Contents of a Jar File

The first thing that we'll want to do is to open the jar file. This is easily done by creating a new java.util.jar.JarFile instance.

try {
    JarFile jarFile = new JarFile("test.jar");
} catch (Exception e) {
    e.printStackTrace();
}
                

The next thing is to enumerate through the jar entries. We get an Enumeration that contains java.util.zip.ZipEntry instances. We then simply print out the name of each entry.

Enumeration entries = jarFile.entries();
while (entries.hasMoreElements()) {
    ZipEntry entry = (ZipEntry) entries.nextElement();
	System.out.println(entry.getName());
}
                

The last thing we need to do is to close the Jar file.

jarFile.close();
                

Running this program will print out all the entries in the jar file named test.jar.

Extracting a File from a Jar File

Extracting a file from a Jar file is a little more tricky since we have to use some IO classes to do the dirty work for use. We can create the Jar file as we did in the previous section and we can get the entry by its name. We will use the jar entry to get an input stream to it as follows:

JarFile jarFile = new JarFile("test.jar");
InputStream in = jarFile.getInputStream(
    jarFile.getEntry("META-INF/MANIFEST.MF"));
                

We then create an output stream to a file.

OutputStream out = new FileOutputStream("manifest.mf");
                

We then copy the data from the input stream into the output stream.

int c;
while ((c = in.read()) != -1)
    out.write(c);
                

Finally we close the streams and the Jar file.

in.close();
out.close();
jarFile.close();
                

Running this program will output the Jar file's manifest to a file named manifest.mf.

Summary

A Java Archive File, commonly referred to as a Jar File is nothing more than a compressed archive using the Zip compression algorithm. Jar files are used to package Java programs and makes them easy to distribute. We can also access Jar files from within our Java programs.

Exercise Set

Multiple Choice

  1. A Jar File is a compressed archive file.

    1. True
    2. False
  2. The Java Archive must be compressed.

    1. True
    2. False
  3. Benefits of using Jar Files are:

    1. Security
    2. Decreased download time
    3. Package Versioning
    4. Portability
    5. All the Above
  4. Which command is used to create a jar file?

    1. java -jar project.jar
    2. jar tf jar-filename
    3. jar cf jar-filename input-files
    4. jar xf jar-filename archived-files
    5. jar cmf seal.txt myJar.jar MyCompany
  5. Which command is used to view the contents of a Jar file?

    1. java -jar project.jar
    2. jar tf jar-filename
    3. jar cf jar-filename input-files
    4. jar xf jar-filename archived-files
    5. jar cmf seal.txt myJar.jar MyCompany
  6. Which command is used to add information to the Manifest file when creating the Jar file?

    1. java -jar project.jar
    2. jar tf jar-filename
    3. jar cf jar-filename input-files
    4. jar xf jar-filename archived-files
    5. jar cmf seal.txt myJar.jar MyCompany
  7. Which command is used to run a program bundled in a Jar file?

    1. java -jar project.jar
    2. jar tf jar-filename
    3. jar cf jar-filename input-files
    4. jar xf jar-filename archived-files
    5. jar cmf seal.txt myJar.jar MyCompany
  8. Which command is used to extract the contents of a Jar file?

    1. java -jar project.jar
    2. jar tf jar-filename
    3. jar cf jar-filename input-files
    4. jar xf jar-filename archived-files
    5. jar cmf seal.txt myJar.jar MyCompany
  9. The class containing the main method in a program is named net.sourceforge.jinit.Main. What entry will go in the manifest file?

    1. Main-Class: Main
    2. Class-Path: net/sourceforge/jinit
    3. Main-Class: net.sourceforge.jinit.Main
    4. Class-Path: net.sourceforge.jinit.Main
  10. The JarFile#getEntry method retuns a?

    1. JarEntry
    2. ZipEntry

Exercises

  1. Find out about the other options to the jar command.

Programming Exercises

  1. Complete the following:
    1. Write a Java program to extract the contents of a jar file.
    2. Write a program to create a jar file. The contents of the jar file are passed as a command line parameter to the program.