1 overview

Run a single Java file into an executable JAR package using JDK jars and Java.

It can be done using an IDE as well, and using Maven only requires a simple package, but a single file doesn’t have to be so nasty.

2 Create a test file

Famous Hello World:

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

3 to compile

In other words, you need to compile the jar package first. You are advised to create a temporary folder to store the class file.

mkdir test && mv Main.java test && cd test;
javac Main.java
Copy the code

4 pack

jar --create --verbose --file Main.jar --main-class Main *.class
Copy the code

Specify the parameters:

  • --create: create a jar
  • --verbose: Generates output when packaging
  • --file: File name of the packaged JAR
  • --main-class: Specifies the entry class
  • *.class: package all class files, where the acceptable arguments can be*“Is used to package all files in the specified directory. The value can also be a directory name

The default package is used here. If a custom package is used, use

--main-class com.xxx.xxx.Main
Copy the code

Can.

Note that some tutorials on the web use abbreviations when packing:

jar -cvf Main.jar *.class
Copy the code

This does work, but running it directly will prompt:

no main manifest attribute, in Main.jar
Copy the code

You can add –main-class or update the manifest.mf file in the package and add:

Main-Class: Main
Copy the code

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

5 run

java -jar Main.jar
Copy the code