A JAR (Java ARchive) is platform-independent file format used to aggregate many Java class files and associated metadata and resources such as text, images, etc, into a single file for distribution.

 

It allows Java runtimes to efficiently deploy an entire application in one archive file, and provides many benefits such as security, its elements may be compressed, shortening download times, allows for package sealing and versioning, supports portability. It also supports packaging for extensions.

 

In this article, we will show how to create a simple Java application and bundle it into a JAR file, and demonstrate how to execute a .jar file from the Linux terminal.

 

How to Create a JAR File in Linux

 

1. First start by writing a simple Java class with the main method for an application called rootadminzApp, for demonstration purpose.

$ vim rootadminzApp.java

 

Copy and paste the following code to rootadminzApp.java file.

public class rootadminzApp {
	public static void main(String[] args){
		System.out.println(" Just executed rootadminzApp! ");
	}
}

 

Save the file and close it.

 

2. Next, we need to compile and pack the class into a JAR file using the javac and jar utilities as shown.

$ javac -d . rootadminzApp.java
$ ls
$ jar cvf rootadminzapp.jar rootadminzApp.class
$ ls

 

3. Once rootadminzapp.jar created, now you can execute the file using java command as shown.

$ java -jar rootadminzapp.jar

no main manifest attribute, in rootadminzapp.jar

 

From the output of the above command, we encountered an error. The JVM (Java Virtual Machine) couldn’t find our main manifest attribute, thus it could not locate the main class containing the main method (public static void main (String[] args)).

 

The JAR file should have a manifest that contains a line in the form Main-Class:classname that defines the class with the main method that serves as our application’s starting point.

 

4. To fix the above error, we will need to update the JAR file to include a manifest attribute together with our code. Let’s create a MANIFEST.MF file.

$ vim MANIFEST.MF

 

Copy and paste the following line to MANIFEST.MF file.

Main-Class:  rootadminzApp

 

Save the file and let’s add the file MANIFEST.MF to our rootadminzapp.jar using the following command.

$ jar cvmf MANIFEST.MF rootadminzapp.jar rootadminzApp.class

 

5. Finally, when we executed the JAR file again, it should produce the expected result as shown in the output.

$ java -jar rootadminzapp.jar

Just executed rootadminzApp!

 

For more information, see the java, javac and jar command man pages.

$ man java
$ man javac
$ man jar

 

Помог ли вам данный ответ? 0 Пользователи нашли это полезным (0 голосов)