What is a JAR file

  • A JAR package is a Java Archive File, a Document format in Java. A JAR package is very similar to a ZIP file — essentially, it is a ZIP file. The only difference between a JAR file and a ZIP file is that the JAR file contains a meta-INF/manifest.mf file, which is automatically generated when the JAR file is generated.

How to open JAR package

  • In the JVM,.class bytecodes are actually parsed, not.java files, and it is generally not recommended to include code source files in JAR packages. So, the process of unpacking the JAR actually wraps the.class file.

compile

  • First, create a new test. Java file and write the Java code for HelloWorld inside.
class test {
    public static void main(String[] agrs) {
        System.out.println("hello world!"); }}Copy the code
  • Then, execute the javac command to compile test.java.
javac test.java -d build
Copy the code
  • Put the test. Java compiled. Class file in the build folder. Then you can go to the build folder and type the JAR package.

Modify the MANIFEST. MF

  • Once in the build folder, you first need to create the manifest.mf file by executing the following command.
jar -cvf test.jar test.class
Copy the code
  • In the above command, c means to create a new JAR package, v means to print some information about the creation process on the console during the creation process, and f means to name the JAR package created
  • If you open the test.jar file, you’ll find a meta-INF folder containing the MENIFEST.MF file.
Manifest-Version: 1.0
Created-By: 11 (Oracle Corporation)
Copy the code
  • The JAR cannot be executed because it is not known which main function needs to be executed. So we add main-class to specify which Main function to execute. Main-class specifies the full path name of the Main Class. The colon must be followed by a space. The entire file must have a blank line. The complete modified file is as follows:
Manifest-Version: 1.0
Created-By: 11 (Oracle Corporation)
Main-Class: test

Copy the code

packaging

  • Then run the following command to print the JAR package that can be directly executed.
jar -cvfm test.jar META-INF/MANIFEST.MF test.class 
Copy the code
  • The added parameter m indicates that the manifest.mf file is defined.

perform

  • Finally, execute the following command to print in the consolehello world!.
java -jar test.jar
Copy the code