tags:

views:

890

answers:

4

I created a JAR file like this:

jar cf Predit.jar *.*

I ran this JAR file by doubling clicking (it does not work). So I ran it from the DOS prompt like this:

java -jar Predit.jar

It raised "Fail 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

+9  A: 

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

Sun'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

Then run:

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

Output:

Hello world
Jon Skeet
+1  A: 

You have to add a manifest to the jar, which tell 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.

Florian
Just of of curiosity, is the 'Meta-inf' subfolder name case sensitive? I have traditionally seen it spelled 'META-INF'
Adam Paynter
You're right. The spec says "META-INF" and does not say anything about case insensitivity (http://java.sun.com/j2se/1.4.2/docs/guide/jar/jar.html#The%20META-INF%20directory)
Florian
+1  A: 

If you don't want to deal with those details, you can also use the export jar assistants from Eclipse or NetBeans.

fortran
A: 

If you don`t want to create a manifest just to run the jar file, you can reference the main-class directly from the command line when you run the jar file.

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

This sets the which main-class to run in the jar file.

Egil