Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a JAR file

Tags:

java

jar

People also ask

What is the Java command to run a JAR file?

To run an application in a nonexecutable JAR file, we have to use -cp option instead of -jar. We'll use the -cp option (short for classpath) to specify the JAR file that contains the class file we want to execute: java -cp jar-file-name main-class-name [args …]


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

Before run the jar check Main-Class: classname is available or not in MANIFEST.MF file. MANIFEST.MF is present in jar.

java -jar filename.jar

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.


A very simple approach to create .class, .jar file.

Executing the jar file. No need to worry too much about manifest file. Make it simple and elgant.

Java sample Hello World Program

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

Compiling the class file

javac HelloWorld.java

Creating the jar file

jar cvfe HelloWorld.jar HelloWorld HelloWorld.class

or

jar cvfe HelloWorld.jar HelloWorld *.class

Running the jar file

 java -jar HelloWorld.jar

Or

java -cp HelloWorld.jar HelloWorld

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.