Home  >  Core Java

Add Manifest into JAR File Using Java

By Arvind Rai, March 04, 2014
In java while creating jar programmatically, we need to add MANIFEST.MF file. Java provides java.util.jar.Manifest class that is used to add manifest file while creating jar. To add manifest file in jar, we need to take help of Manifest, Attributes.Name and JarOutputStream. We will see step by step process to add manifest file.

Creating Manifest Object

To create manifest object, we need to simply call a constructor as given below
Manifest manifest = new Manifest();
 

Use Attributes.Name to add attributes

To add attributes, fetch Attributes from manifest object and add the required attribute name.
Attributes global = manifest.getMainAttributes(); 
global.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
 



Create the Jar

Now finally create the jar using JarOutputStream as given below
JarOutputStream jos =  new JarOutputStream(os, manifest);
 
Find the complete example.
JarOutputStreamDemo.java
package com.concretepage.util.jar;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.jar.Attributes;
import java.util.jar.JarOutputStream;
import java.util.jar.Manifest;
public class JarOutputStreamDemo {
    public static void main(String[] args) throws IOException {
        //prepare Manifest file
        Manifest manifest = new Manifest();
        Attributes global = manifest.getMainAttributes();
        global.put(Attributes.Name.MANIFEST_VERSION, "1.0.0");
        global.put(new Attributes.Name("Created-By"), "concretepage");
        global.put(new Attributes.Name("CLASS_PATH"), "dummy classpath");
        global.put(new Attributes.Name("CONTENT_TYPE"), "txt/plain");
        global.put(new Attributes.Name("SIGNATURE_VERSION"), "2.0");
        global.put(new Attributes.Name("SPECIFICATION_TITLE"), "dummy title");
        global.put(new Attributes.Name("CLASS_PATH"), "dummy classpath");
       
        //create required jar name
        String jarFileName ="D:/cp/jar/cp.jar";
        JarOutputStream jos = null;
        try {
           File jarFile = new File(jarFileName);
           OutputStream os = new FileOutputStream(jarFile);
           jos = new JarOutputStream(os, manifest);
        } catch (IOException e) {
              e.printStackTrace();
        }
        jos.close();
        System.out.println("Done");
    }
}
  
Check the location of jar and fetch MANIFEST.MF file within the jar, you will be able to get manifest file which will contain the below data
Manifest-Version: 1.0.0
SIGNATURE_VERSION: 2.0
SPECIFICATION_TITLE: dummy title
Created-By: concretepage
CONTENT_TYPE: txt/plain
CLASS_PATH: dummy classpath
 
POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us