How to create Jar file in using java commands?

Before looking at how, let’s look into, what is a JAR file?

A JAR file bundles multiple .class files, resources (images, properties), and metadata into one compressed package — similar to a .zip — so it’s easier to distribute and run a Java application.

Steps to Create a JAR File (Using Command Line)

1. Compile your Java code

javac HelloWorld.java

-> This will create a HelloWorld.class file.

2. Create a Manifest file (optional but important for executable JAR)

Create a file named manifest.txt with this content:

Main-Class: HelloWorld

-> Ensure there is a blank line at the end of the file (important for correct manifest format).

3. Create the JAR file

Now, use the jar command:

jar cfm MyApp.jar manifest.txt HelloWorld.class

Where:

  • c → Create new JAR
  • f → Specify output file name
  • m → Include manifest file
  • MyApp.jar → Name of the jar file
  • manifest.txt → Manifest file you created
  • HelloWorld.class → Compiled class(es) to include

4. Run the JAR file

java -jar MyApp.jar

Examples of Other Common jar Commands

PurposeCommand
Create JAR without manifestjar cf MyLib.jar *.class
View contents of a JARjar tf MyApp.jar
Extract JAR contentsjar xf MyApp.jar
Update existing JARjar uf MyApp.jar NewClass.class

Leave a Reply

Your email address will not be published. Required fields are marked *