How to run a JAR file

一、Setting an Application’s Entry Point

If you have an application bundled in a JAR file, you need some way to indicate which class within the JAR file is your application’s entry point. You provide this information with the Main-Class header in the manifest, which has the general form:

Main-Class: classname

Warning: 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.
The value classname is the name of the class that is your application’s entry point.

Recall that the entry point is a class having a method with signature public static void main(String[] args).

We then create a JAR file named MyJar.jar by entering the following command:

jar cfm MyJar.jar Manifest.txt MyPackage/*.class

After you have set the Main-Class header in the manifest, you then run the JAR file using the following form of the java command:

java -jar JAR-name

The main method of the class specified in the Main-Class header is executed.

An Example

MANIFEST.MF
注意:最后一行必须为空行

Manifest-Version: 1.0
Main-Class: Test

Test.java

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

build_jar.bat

javac Test.java
jar cfm test.jar MANIFEST.MF Test.class
del Test.class
java -jar test.jar
del test.jar

二、Setting an Entry Point with the JAR Tool

The ‘e’ flag (for ‘entrypoint’) creates or overrides the manifest’s Main-Class attribute. It can be used while creating or updating a JAR file. Use it to specify the application entry point without editing or creating the manifest file.

For example, this command creates app.jar where the Main-Class attribute value in the manifest is set to MyApp:

jar cfe app.jar MyApp MyApp.class

You can directly invoke this application by running the following command:

java -jar app.jar

If the entrypoint class name is in a package it may use a ‘.’ (dot) character as the delimiter. For example, if Main.class is in a package called foo the entry point can be specified in the following ways:

jar cfe Main.jar foo.Main foo/Main.class
An Example

HelloWorld.java

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

build_jar.bat

javac HelloWorld.java
jar cvfe HelloWorld.jar HelloWorld HelloWorld.class
:: jar cvfe HelloWorld.jar HelloWorld *.class
java -jar HelloWorld.jar
::java -cp HelloWorld.jar HelloWorld
::java -jar HelloWorld.jar -classpath HelloWorld
del HelloWorld.class
del HelloWorld.jar

Reference

  1. How to run a JAR file
  2. Setting an Application’s Entry Point
  • 15
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值