1 overview

Run a single Java file as an executable JAR using the JAR that comes with the JDK and Java. It can also be done using an IDE. Maven requires only a simple package, but a single file doesn’t have to be so “brutal”.

2 Create a new test file

The famous Hello World:

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

3 to compile

It is recommended to create a temporary folder to store the class files first.

mkdir test && mv Main.java test && cd test;
javac Main.java

4 pack

jar --create --verbose --file Main.jar --main-class Main *.class

Explain the parameters:

  • --create: create a jar
  • --verbose: Output is produced when packaging
  • --file: The packaged JAR filename
  • --main-class: Specifies the entry class
  • *.class: Package all class files, where the acceptable parameters can be*, package all the files in the directory, or can be the directory name, package all the files in the specified directory

The default package is used here, or if a custom package is used

--main-class com.xxx.xxx.Main


Note that some tutorials on the web use shorthand when packaging:

jar -cvf Main.jar *.class

This is packable, but when run directly it will prompt:

no main manifest attribute, in Main.jar

You can add the –main-class parameter or update the MANIFEST.MF file directly after packaging by adding:

Main-Class: Main

Of course, it is recommended to use the above method to package in one step.

5 run

java -jar Main.jar