Add Manifest into JAR File Using Java
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 belowManifest manifest = new Manifest();
2. Use Attributes.Name for attributes
To add attributes, fetchAttributes
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 belowJarOutputStream jos = new JarOutputStream(os, manifest);
4. Complete Example
JarOutputStreamDemo.javapackage 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"); } }
Manifest-Version: 1.0.0 SIGNATURE_VERSION: 2.0 SPECIFICATION_TITLE: dummy title Created-By: concretepage CONTENT_TYPE: txt/plain CLASS_PATH: dummy classpath