Add Manifest into JAR File Using Java

By Arvind Rai, November 17, 2023
On this page, we will learn to add MANIFEST.MF file programmatically in JAR. Java provides java.util.jar.Manifest class to create MANIFEST.MF file.
Find the example to add manifest file step-by-step.

1. Creating Manifest Object

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

2. Use Attributes.Name for 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"); 

3. Create the Jar

Now finally create the JAR using JarOutputStream as given below
JarOutputStream jos =  new JarOutputStream(os, manifest); 

4. 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 from JAR, we 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







©2024 concretepage.com | Privacy Policy | Contact Us