Recipe 23.4 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

Creating 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 Recipe 7.7), and elsewhere. Some attributes are required by the application, while others are optional. For example, Recipe 23.7 discusses running a main program directly from a JAR; this requires a Main-Program header. You can even invent your own attributes, such as:

MySillyAttribute: true MySillynessLevel: high (5'11")

You store this in a file called, say, manifest.stub,[3] and pass it to jar with the -m switch. jar includes your attributes in the manifest file it creates:

[3] Some people like to use names like MyPackage.mf so that it's clear which package it is for; the extension .mf is arbitrary, but it's a good convention for identifying manifest files.

jar -cv -m manifest.stub -f /tmp/com.darwinsys.util.jar .

The jar program and related tools add additional information to the manifest, including a listing of all the other files included in the archive.



Java Cookbook
Java Cookbook, Second Edition
ISBN: 0596007019
EAN: 2147483647
Year: 2003
Pages: 409
Authors: Ian F Darwin

Similar book on Amazon

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net