How to run a JAR file

I created a JAR file like this:

jar cf Predit.jar *.*

I ran this JAR file by double clicking on it (it didn't work). So I ran it from the DOS prompt like this:

java -jar Predit.jar

It raised "Failed to load main class" exceptions. So I extracted this JAR file:

jar -xf Predit.jar

and I ran the class file:

java Predit

It worked well. I do not know why the JAR file did not work. Please tell me the steps to run the JAR file


You need to specify a Main-Class in the jar file manifest.

Oracle's tutorial contains a complete demonstration, but here's another one from scratch. You need two files:

Test.java:

public class Test
{
    public static void main(String[] args)
    {
        System.out.println("Hello world");
    }
}

manifest.mf:

Manifest-version: 1.0
Main-Class: Test

Note that the text file must end with a new line or carriage return. The last line will not be parsed properly if it does not end with a new line or carriage return.

Then run:

javac Test.java
jar cfm test.jar manifest.mf Test.class
java -jar test.jar

Output:

Hello world

java -classpath Predit.jar your.package.name.MainClass

You have to add a manifest to the jar, which tells the java runtime what the main class is. Create a file 'Manifest.mf' with the following content:

Manifest-Version: 1.0
Main-Class: your.programs.MainClass

Change 'your.programs.MainClass' to your actual main class. Now put the file into the Jar-file, in a subfolder named 'META-INF'. You can use any ZIP-utility for that.

链接地址: http://www.djcxy.com/p/55016.html

上一篇: 来自JAR文件的类清单属性?

下一篇: 如何运行JAR文件