Java - JAR File API

Introduction

An object of the Manifest class represents a manifest file.

You create a Manifest object in your code as follows:

Manifest manifest = new Manifest();

To add an entry into a main section, get an instance of the Attributes class using the getMainAttributes() of Manifest class.

Add a name-value pair to it using its put() method.

Example

The following code adds some attributes to the main section of a manifest object.

The attribute names are defined as constants in the Attributes.Name class.

For example, the constant Attributes.Name.MANIFEST_VERSION represents the Manifest-Version attribute name.

Manifest manifest = new Manifest();
Attributes mainAttribs = manifest.getMainAttributes();
mainAttribs.put(Attributes.Name.MANIFEST_VERSION, "1.0");
mainAttribs.put(Attributes.Name.MAIN_CLASS, "com.book2s.intro.Welcome");
mainAttribs.put(Attributes.Name.SEALED, "true");

Add the following individual entry to a manifest file:

Name: "com/book2s/archives/"
Sealed: false

The following code adds an individual entry to a Manifest object:

// Get the Attribute map for the Manifest
Map<String,Attributes> attribsMap = manifest.getEntries();

// Create an Attributes object
Attributes attribs = new Attributes();

// Create an Attributes.Name object for the "Sealed" attribute
Attributes.Name name = new Attributes.Name("Sealed");

// Add the "name: value" pair (Sealed: false) to the attributes objects
attribs.put(name, "false");

// Add the Sealed: false attibute to the attributes map
attribsMap.put("com/book2s/archives/", attribs);

To add a manifest file to a JAR file, specify it in one of the constructors of the JarOutputStream class.

The following code creates a jar output stream to create a test.jar file with a Manifest object:

// Create a Manifest object
Manifest manifest = new Manifest();

// Create a JarOutputStream with a Manifest object
JarOutputStream jos = new JarOutputStream(new BufferedOutputStream(
                          new FileOutputStream("test.jar")), manifest);

Related Topics