The JAR file (Java Archive) is a way to compress multiple files in Java, as well as a ZIP. Usually the classes and other configuration files are stored. As they grouped several classes in a single file, they are great for distributing libraries, such as database drivers, frameworks, systems modules, etc.
We can also create an executable JAR, which contains a class with the method main, and using the JVM, we can run it. To generate a JAR file, view or extract the file contents, use the same name program, the jar, which is distributed with the Java Development Kit (JDK).
Generating executable JAR files
We will create a program that receives user’s weight and height, BMI calculates and prints on the screen the result. So we can see the process of creating and running an executable JAR.
We will not use any IDE to support this procedure, to demonstrate how to use the tool.
The class must have the following code in the main method.
try (Scanner input = new Scanner (System.in)) { input.useLocale (new Locale ("en", "US")); System.out.print ("Enter your weight:"); double weight = input.nextDouble (); System.out.print ("Enter your height:"); double height = input.nextDouble(); double imc = weight / (height * height); System.out.printf ("BMI:%.2f \n" imc);
We will compile the class using javac.
$Javac Main.java
The manifest.txt file should contain the name of the class that has the main method. Look content below:
Now it’s time to generate the JAR file. Let’s run the following command.
$jar cfm imc.jar Manifest.txt Main.class
The command is saying to create a imc.jar file with the main class and a MANIFEST.MF file in the META-INF directory.
The MANIFEST.MF file is read at run time to find out which class has the main method, and contain other information such as the version of the JDK used for its creation.