21. The Java Development Kit

21.1. The Java Archiver jar Tool

 

The jar tool can be used to combine multiple files into a single JAR archive file. Although the jar tool is a general-purpose archiving and compression tool, it was designed mainly to facilitate the packaging of Java applets and applications into a single file.

The main justification for combining files into a single archive and compressing the archive is to improve download time. The jar command takes the following format:

 

 

 

jar [ options ] destination-file input-file [ input-files ]

 

 

 

For an example of its usage, let’s use it to archive the files involved in the WordGuess example in Chapter 9. As you may recall, this example used classes, such as TwoPlayerGame, and interfaces, such as IGame, that were developed in earlier sections of the chapter. So, to help manage the development of WordGuess, it would be useful to have a library containing those files that must be linked together when we compile WordGuess.

This is a perfect use of a jar file. Let’s name our library nplayerlib.jar. We choose this name because the library can be used to create game programs that have N players, including two-player games.

 

For the two-player game, WordGuess, we want to combine all the .class files needed by WordGuess.java into a single jar file. Here’s a list of the files we want to archive:

,,

 

 

 

 

 

J

Assuming all of these files are contained in a single directory (along with other files, perhaps), then the command we use from within that directory is as follows:

,,

 

J

In this case, the cf options specify that we are creating a jar file named animated.jar that will consist of all the files having the .class suffix. This will create a file named nplayerlib.jar. To list the contents of this file, you can use the following command:

,,

 

J

Once we have created the jar file, we can copy it into the directory that contains our source code for the WordGuess program. We would then the following com- mands to include the code contained in the library when we compile and run WordGuess.java

,,

 

J

These commands, which use the -classpath option, tell javac and java to in- clude code from the nplayerlib.jar. The notation :., links code in the current directory ()˙ with the library code.

Once we have created a library, we can also use it for Java applets. For exam- ple, suppose we have developed an applet version of the WordGuess game and linked all of the applet’s code into a jar file named wordguessapplet.jar. The

 

following HTML file would allow users to download the applet from their web browser:

,,

 

 

 

 

 

 

 

 

 

J

When specified in this way, the browser will take care of downloading the archive file and extracting the individual files needed by the applet. Note that the code attribute must still designate the file where the program will start execution.