Skip to main content

Having trouble creating a Jar with MANIFEST.MF?

Posted by ss141213 on October 13, 2009 at 2:33 AM PDT

When my colleague Marina Vatkina sent me some code earlier today hoping a second pair of eyes would spot the obvious error, knowing how thorough Marina typically is, I knew there was no obvious error there. Simplified version of what was being attempted is shown below:

import java.io.*;
import java.util.*;
import java.util.jar.*;

public class CreateJarWithManifest {
    public static void main(String[] a) throws Exception {
        Manifest manifest = new Manifest();
        manifest.getMainAttributes().putValue("Foo", "Bar");
        FileOutputStream fo = new FileOutputStream(new File("foo.jar"));
        JarOutputStream jo = new JarOutputStream(fo, manifest);
        jo.close();
        fo.close();
        new JarFile("foo.jar").getManifest().write(System.out);
    }
}

As you can see, the above code is creating a new Jar file with a manifest entry Foo: Bar and then reads the manifest from the jar and prints it to output for verification purpose. But, strangely this program prints an empty manifest. I vaguely remembered to have encountered this problem before, but never wrote it down anywhere. It took some time to figure out here and that's why I thought of putting it down here this time. The problem here is that if there is no attribute called Manifest-Version in the main section, the manifest is simply ignored. So, for the above code to work, we need something like this:

        manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");

I don't understand why new Manifest() does not populate this attribute automatically. Even worse, why is there no warning or exception reported when such a manifest is used.

Related Topics >>

Comments

Good point!

Why not file a bug report to improve this?