A single java file is converted into an executable jar package

Posted Jun 16, 20201 min read

1 Overview

Use JDK's own jar and java to convert a single java file into an executable jar package and run it.
Of course, it can also be done with an IDE. Using Maven only requires a simple package, but for a single file, there is no need to be so fierce.

2 New test file

The famous Hello World:

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

3 Compile

The class file is required to generate the jar package. In other words, it needs to be compiled first. It is recommended to create a temporary folder to store the class file.

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

4 Packaging

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

Explain the various parameters:

  • --create:create jar
  • --verbose:output when packaging
  • --file:the name of the packaged jar file
  • --main-class:specify the entry class
  • *.class:package all class files, the acceptable parameter here can be *, which means that all files in this directory are packaged, or it can be the name of the directory, and package all files in the specified directory

The default package is used here, if it is a custom package, use

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

That's it.

Note that there are shorthands for online tutorials when packaging:

jar -cvf Main.jar *.class

This can indeed be packaged, but it will prompt when running directly:

no main manifest attribute, in Main.jar

You can add the --main-class parameter or directly update the MANIFEST.mf file inside the package, plus:


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

5 Run

java -jar Main.jar