Jar manifest example - how to add a manifest file to a jar file

Summary: How to add a manifest file to a Java jar file.

I just created an executable jar file for a Java client-side application. I hadn't done this in a while, and I always forget about the option to include a manifest file in the jar file. If you're good and remember to include a manifest file, like this:

jar cfm curtain.jar Manifest.txt com/

then users can run your client application very simply, like this:

java -jar curtain.jar

But, if you don't include a manifest file and users try to run your application like that they will instead get a nice error message, like this:

Failed to load Main-Class manifest attribute from curtain.jar

FWIW, my manifest file, Manifest.txt, just has one line in it, telling the Java interpreter where to find the main method it needs to start running the application, like this:

Main-Class: com.devdaily.curtaindemo.CurtainDemoMain

Actually, this file has two lines in it. It seems there is a bug somewhere in the process, and you need to make sure that your one line has a carriage return at the end, so I put a blank line after the line shown above. (Sometimes I am truly amazed that we got people to the moon.)

You can see all the jar command options by just typing jar at the command line. For the Java 1.5 (5.0) platform you'll see help like this:

Usage: jar {ctxu}[vfm0Mi] [jar-file] [manifest-file] [-C dir] files ...

Options:
    -c  create new archive
    -t  list table of contents for archive
    -x  extract named (or all) files from archive
    -u  update existing archive
    -v  generate verbose output on standard output
    -f  specify archive file name
    -m  include manifest information from specified manifest file
    -0  store only; use no ZIP compression
    -M  do not create a manifest file for the entries
    -i  generate index information for the specified jar files
    -C  change to the specified directory and include the following file

If any file is a directory then it is processed recursively.
The manifest file name and the archive file name needs to be specified
in the same order the 'm' and 'f' flags are specified.

Example 1: to archive two class files into an archive called classes.jar: 

    jar cvf classes.jar Foo.class Bar.class 

Example 2: use an existing manifest file 'mymanifest' and archive all the files in the foo/ directory into 'classes.jar': 

    jar cvfm classes.jar mymanifest -C foo/ .

So as you can see from that last line, this is the manual way to include a Java manifest in a Jar file:

jar cvfm classes.jar mymanifest -C foo/ .

Finally, while this approach is good for the "one off" (rare) project, a much better approach is to Build a Jar manifest file with Ant.