Enable your unrunnable JARs to run with the java -jar command

转贴一篇来自http://www.javaworld.com/文章
这篇文章介绍了如何通过一个java程序来自动在manifest.mf中添加Main-Class,使得jar文件可以直接运行。

Enable your unrunnable JARs to run with the java -jar command

By Shawn Silverman

Summary
This tip shows how to turn an unrunnable Java Archive (JAR) into a runnable one, without having to directly manipulate manifest files. You learn to develop a short program that enables any JAR to run with the java -jar command or on an operating system like Windows with just a double click. (1,100 words; May 10, 2002)


You can easily package an application's entire set of classes and resources into a Java Archive (JAR). In fact, that is one goal of having jar files. Another is to let users easily execute the application stored in the archive. Why then are jar files second-class citizens in the Java universe—functioning only as archives—when they can be first class, right alongside native executables?

To execute a jar file, you can use the java command's -jar option. For example, say you have a runnable jar file called myjar.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?

The manifest file and the Main-Class entry
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 command which class to execute.

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.

Let the API do it for you
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 JAR we wish to make runnable
The main class we wish to execute (this class must exist inside the JAR)
The name of a new JAR for our output, because we shouldn't simply overwrite files
Write the program
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?

Check the arguments to main
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 "
                           + " ");
        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.

Access the JAR and its manifest file
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();
    }


Set the Main-Class attribute
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:


    Attributes a = manifest.getMainAttributes();
    String oldMainClass = a.putValue("Main-Class", args[1]);

    //If an old value exists, tell the user and exit

    if (oldMainClass != null) {
        System.out.println("Warning: old Main-Class value is: "
                           + oldMainClass);
        System.exit(1);
    }


Output the new JAR
We need to create a new jar file, so we must use the JarOutputStream class. Note: We must ensure we don't use the same file for output as we do for input. Alternatively, perhaps the program should consider the case where the two jar files are the same and prompt the user if he wishes to overwrite the original. However, I reserve this as an exercise for the reader. On with the code!


    System.out.println("Writing to " + args[2] + "...");
    JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(args[2]),
                                                 manifest);


We must write every entry from the input JAR to the output JAR, so iterate over the entries:


    //Create a read buffer to transfer data from the input

    byte[] buf = new byte[4096];

    //Iterate the entries

    JarEntry entry;
    while ((entry = jarIn.getNextJarEntry()) != null) {
        //Exclude the manifest file from the old JAR

        if ("META-INF/MANIFEST.MF".equals(entry.getName())) continue;

        //Write the entry to the output JAR

        jarOut.putNextEntry(entry);
        int read;
        while ((read = jarIn.read(buf)) != -1) {
            jarOut.write(buf, 0, read);
        }

        jarOut.closeEntry();
    }

    //Flush and close all the streams

    jarOut.flush();
    jarOut.close();

    jarIn.close();


Complete program
Of course, we must place this code inside a main method, inside a class, and with a suitable set of import statements. The Resources section provides the complete program.

Usage example
Let's put this program to use with an example. Suppose you have an application whose main entry point is in a class called HelloRunnableWorld. (This is the full class name.) Also assume that you've created a JAR called myjar.jar, containing the entire application. Run MakeJarRunnable on this jar file like so:


    java MakeJarRunnable myjar.jar HelloRunnableWorld myjar_r.jar


Again, as mentioned earlier, notice how I order the argument list. If you forget the order, just run this program with no arguments and it will respond with a usage message.

Try to run the java -jar command on myjar.jar and then on myjar_r.jar. Note the difference! After you've done that, explore the manifest files (META-INF/MANIFEST.MF) in each JAR. (You can find both JARs in the source code.)

Here's a suggestion: Try to make the MakeJarRunnable program into a runnable JAR!

Run with it
Running a JAR by double-clicking it or using a simple command is always more convenient than having to include it in your classpath and running a specific main class. To help you do this, the JAR specification provides a Main-Class attribute for the JAR's manifest file. The program I present here lets you utilize Java's JAR API to easily manipulate this attribute and make your JARs runnable.


About the author
Shawn Silverman is currently a graduate student in the department of electrical and computer engineering at the University of Manitoba in Canada. He started working with Java in mid-1996, and has been using it almost exclusively ever since. His current interests include the simulation of electric fields and fluids, error-correcting codes, and the implementation of nifty GUI (graphical user interface) tricks. Shawn also teaches a third-year software design course in the computer engineering department at his university.


Resources

Download the source code and JARs for this tip:
http://www.javaworld.com/javaworld/javatips/javatip127/MakeJarRunnable.zip

"Java Tip 120: Execute Self-Extracting JARs," Z. Steve Jin and John D. Mitchell (JavaWorld, November 2001):
http://www.javaworld.com/javaworld/javatips/jw-javatip120.html

JAR File Specification:
http://java.sun.com/j2se/1.3/docs/guide/jar/jar.html

jar—The Java Archive Tool:
http://java.sun.com/j2se/1.3/docs/tooldocs/win32/jar.html

View all previous Java Tips and submit your own:
http://www.javaworld.com/javatips/jw-javatips.index.html

Learn Java from the ground up in JavaWorld's Java 101 column:
http://www.javaworld.com/javaworld/topicalindex/jw-ti-java101.html

Java experts answer your toughest Java questions in JavaWorld's Java Q&A column:
http://www.javaworld.com/javaworld/javaqa/javaqa-index.html

Browse the Core Java section of JavaWorld's Topical Index:
http://www.javaworld.com/channel_content/jw-core-index.shtml

Stay on top of our Tips 'N Tricks by subscribing to JavaWorld's free weekly email newsletters:
http://www.javaworld.com/subscribe

Learn the basics of client-side Java in JavaWorld's Java Beginner discussion. Core topics include the Java language, the Java Virtual Machine, APIs, and development tools:
http://forums.devworld.com/webx?50@@.ee6b804

You'll find a wealth of IT-related articles from our sister publications at IDG.net

-------------------------------------------------------

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.jar.*;

/**
 * This utility makes a JAR runnable by inserting a <code>Main-Class</code>
 * attribute into the Manifest.
 *
 * @author Shawn Silverman
 */
public class MakeJarRunnable {
    public static void main(String[] args) throws IOException {
        if (args.length != 3) {
            System.out.println("Usage: MakeJarRunnable "
                               + "<jar file> <Main-Class> <output>");
            System.exit(0);
        }

        // 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 there is no Manifest

            manifest = new Manifest();
        }

        Attributes a = manifest.getMainAttributes();
        String oldMainClass = a.putValue("Main-Class", args[1]);

        // If there was an old value there, tell the user about it and exit

        if (oldMainClass != null) {
            System.out.println("Warning: old Main-Class value is: "
                               + oldMainClass);
            System.exit(1);
        }

        System.out.println("Writing to " + args[2] + "...");
        JarOutputStream jarOut = new JarOutputStream(new FileOutputStream(args[2]),
                                                     manifest);

        // Create a read buffer to be used for transferring data from the input

        byte[] buf = new byte[4096];

        // Iterate the entries

        JarEntry entry;
        while ((entry = jarIn.getNextJarEntry()) != null) {
            // Exclude the Manifest file from the old JAR

            if ("META-INF/MANIFEST.MF".equals(entry.getName())) continue;

            // Write out the entry to the output JAR

            jarOut.putNextEntry(entry);
            int read;
            while ((read = jarIn.read(buf)) != -1) {
                jarOut.write(buf, 0, read);
            }

            jarOut.closeEntry();
        }

        // Flush and close all the streams

        jarOut.flush();
        jarOut.close();

        jarIn.close();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值