A JAR(Java Archive) is a platform-independent file that allows you to easily deploy Java Applications in one place. It can be used to aggregate classes, images, text files into a single file for distribution. It improves application security, allows package versioning and enhances portability. In this article, we will learn how to bundle a Java application into a JAR file and how to execute .jar file from Linux command.
How to Create & Execute Jar File in Linux
We have assumed that you have already installed Java command line tool on your system, and you can use it with -jar option to execute a .jar file.
1. Create .java class
First we will create a simple Java class with main method for a demo app called HelloWorld. Create an empty .java file using a text editor.
$ vim HelloWorld.java
Add the following lines to it. It simply prints ‘Hello World’ upon execution.
public class HelloWorld { public static void main(String[] args){ System.out.println("Hello World"); } }
2. Compile & Pack the Class into JAR file
Next you need to compile & pack the class into JAR file using javac & jar commands. Basically we first create a class out of our .java code, using javac command. Then we package the class into a .jar file using jar command.
$ javac -d . HelloWorld.java $ ls $ jar cvf helloworld.jar HelloWorld.class $ ls
3. Create Manifest File
You need to create a separate manifest file, and update the JAR file to include it, in order to execute the JAR file. Create an empty manifest file.
$ vim MANIFEST.MF
Copy and paste the following code in it.
Main-Class: HelloWorld
Save and close the file. Next add the manifest file to the JAR file using the following command.
$ jar cvmf MANIFEST.MF helloworld.jar HelloWorld.class
4. Execute JAR
Once the .jar file is created you can execute it with the following command.
$ java -jar helloworld.jar Hello World
Running the above code produces the desired result. It is important to remember to create a manifest file and add it to the JAR file otherwise you will get the following error.
no main manifest attribute, in helloworld.jar
Whenever you run a JAR file the Java Virtual Machine (JVM) looks for its manifest attribute to locate the main class containing main method. So the JAR file must contain a line of the form Main-Class:classname to point to the class with main method, that serves as every application’s starting point.
In this article, we have learnt how to create and execute JAR files.
Also read:
How to Fix ‘Plain HTTP Request was sent to HTTPS’ Error in NGINX
How to Block USB Storage Device in Linux
How to Disconnect Inactive or Idle SSH Connections
How to Enable Debugging Mode in SSH
How to Copy Column to Another Column in MySQL
Related posts:
Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.