O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Archiving with jar

Problem

You want to create a Java archive (JAR) file.

Solution

Use jar.

Discussion

The jar archiver is Java’s standard tool for building archives. Archives serve the same purpose as the program libraries that some other programming languages use. Java normally loads its standard classes from archives, a fact you can verify by running a simple Hello World program with the -verbose option:

java -verbose HelloWorld

To create an archive is a simple process. The jar tool takes several command-line arguments: the most common are c for create, t for table of contents, and x for extract. The archive name is specified with -f and a filename. The options are followed by the files and directories to be archived. For example:

jar cvf /tmp/MyClasses.jar .

The dot at the end is important; it means “the current directory.” This command creates an archive of all files in the current directory and its subdirectories into the file /tmp/MyClasses.jar.

Some applications of JAR files require an extra file in the JAR called a manifest . This file lists the contents of the JAR and their attributes. The attributes are in the form name: value, as used in email headers, properties files (see Section 7.8), and elsewhere. Some attributes are required by the application, while others are optional. For example, Section 23.7 discusses running a main program directly from a JAR; this requires a Main-Program header. You can even invent your own headers, such as:

MySillyAttribute: true MySillynessLevel: ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required