Skip to main content
Logo image

Java, Java, Java: Object-Oriented Problem Solving, 2024E

Section B.3 The Java Archiver: jar

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 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:
  • CLUIPlayableGame.class
  • ComputerGame.class
  • GUIPlayableGame.class
  • IGame.class
  • KeyboardReader.class
  • Player.class
  • TwoPlayerGame.class
  • UserInterface.class
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:
jar cf nplayerlib.jar *.class
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:
jar tf nplayerlib.jar
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 use the following commands to include the code contained in the library when we compile and run WordGuess.java
javac -classpath nplayerlib.jar:. WordGuess.java
java -classpath nplayerlib.jar:. WordGuess
These commands, which use the -classpath option, tell javac and java to include code from the nplayerlib.jar. The notation :., links code in the current directory (.) with the library code.
You have attempted of activities on this page.