1 Overview
Use the jar and Java provided by JDK to print a single java file into an executable jar package and run it.
Of course, you can also use ide. You only need a simple package to use maven, but you don’t need to be so “fierce” for a single file.
2 new test file
The famous Hello World:
public class Main
{
public static void main(String [] args)
{
System.out.println("Hello world.");
}
}
3 compilation
Class files are required to generate jar packages. In other words, they need to be compiled first. It is recommended to create a temporary folder to store the class files.
mkdir test && mv Main.java test && cd test;
javac Main.java
4 packing
jar --create --verbose --file Main.jar --main-class Main *.class
Describe the parameters as follows:
-
--create
: create jar -
--verbose
: generate output when packaging -
--file
: the name of the packaged jar file -
--main-class
: specify entry class -
*.class
: package all class files. The acceptable parameters here can be*
, means packing all files in the directory, or directory name, packing all files in the specified directory
The default package is used here. If it is a custom package, use the
--main-class com.xxx.xxx.Main
That’s fine.
Note that some online tutorials use abbreviations when packing:
jar -cvf Main.jar *.class
In this way, it can be packaged, but when running directly, you will be prompted:
no main manifest attribute, in Main.jar
Can be added--main-class
Parameters or directly update theMANIFEST.mf
Documents, plus:
Main-Class: Main
Of course, it is recommended to pack in place one step by one using the above methods.
5 operation
java -jar Main.jar