|
|
Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs
To execute a jar file, you can use the java command's
-jarmyjar.jar. Because the file is runnable, you can execute it like this:
java -jar myjar.jar
Alternatively, the Java Runtime Environment (JRE), when installed on an OS like Microsoft Windows, associates jar files with the JVM so you can double-click on them to run the application. These JARs must be runnable.
The question is: How do you make a JAR runnable?
Inside most JARs, a file called MANIFEST.MF is stored in a directory called META-INF. Inside that file, a special entry called Main-Class tells the
java -jar
The problem is that you must properly add this special entry to the manifest file yourself—it must go in a certain place and must have a certain format. However, some of us don't like editing configuration files.
Since Java 1.2, a package called java.util.jar has let you work with jar files. (Note: It builds on the java.util.zip package.) Specifically, the jar package lets you easily manipulate that special manifest file via the Manifest class.
Let's write a program that uses this API. First, this program must know about three things:
The above list will constitute our program's arguments. At this point, let's choose a suitable name for this application.
How does MakeJarRunnable sound?
Assume our main entry point is a standard main(String[]) method. We should first check the program arguments here:
if (args.length != 3) {
System.out.println("Usage: MakeJarRunnable "
+ "<jar file> <Main-Class>
<output>");
System.exit(0);
}
Please pay attention to how the argument list is interpreted, as it is important for the following code. The argument order and contents are not set in stone; however, remember to modify the other code appropriately if you change them.
First, we must create some objects that know about JAR and manifest files:
//Create the JarInputStream object, and get its manifest
JarInputStream jarIn = new JarInputStream(new FileInputStream(args[0]));
Manifest manifest = jarIn.getManifest();
if (manifest == null) {
//This will happen if no manifest exists
manifest = new Manifest();
}
We put the Main-Class entry in the manifest file's main attributes section. Once we obtain this attribute set from the manifest object, we can
set the appropriate main class. However, what if a Main-Class attribute already exists in the original JAR? This program simply prints a warning and exits. Perhaps we could add a command-line
argument that tells the program to use the new value instead of the pre-existing one: