JAR File in Java: Create, Run and Inspect JAR Files
A JAR file in Java (Java ARchive) is a single .jar file that bundles compiled .class files, resources such as images or config files, and a manifest that describes the archive. JAR files are how Java programs and libraries are shipped: every dependency you add with Maven or Gradle is a JAR, and most desktop and server apps are started with java -jar.
In this lesson you will create a JAR with the jar tool, list and extract its contents, make an executable JAR with a Main-Class, write a custom manifest, add and update files, load resources from inside a JAR, read a JAR from Java code, and build an app JAR that depends on a separate library JAR.
What Is Inside a JAR File
A JAR is a ZIP file with a fixed layout. Classes are stored in folders that match their packages, and a special META-INF folder holds the manifest.
greet-app.jar
├── META-INF/
│ └── MANIFEST.MF (metadata: version, Main-Class, Class-Path ...)
└── com/gocourse/greet/
├── Greeter.class
└── Main.class
| Part | Purpose |
|---|---|
Package folders (com/gocourse/greet/) | Let the JVM find classes by their fully qualified names |
META-INF/MANIFEST.MF | Key-value metadata read by the JVM and tools |
Resources (.properties, images, SQL files) | Data files the program loads at runtime |
Note: Because a JAR is a ZIP file, any ZIP tool can open it. Always create JARs with the
jartool or a build tool, though, so the manifest is written correctly.
The jar Command: Options at a Glance
The jar tool ships with every JDK. Each command uses one main mode plus options. Both long (GNU-style) and short forms work.
| Task | Long form | Short form |
|---|---|---|
| Create a JAR | jar --create --file app.jar ... | jar cf app.jar ... |
| List contents | jar --list --file app.jar | jar tf app.jar |
| Extract contents | jar --extract --file app.jar | jar xf app.jar |
| Add or replace files | jar --update --file app.jar ... | jar uf app.jar ... |
| Set the entry point | --main-class com.x.Main | e (as in jar cfe app.jar com.x.Main ...) |
| Use a manifest file | --manifest manifest.txt | m (as in jar cfm app.jar manifest.txt ...) |
| Change directory first | -C out . | -C out . |
| Show each file added | --verbose | v |
This lesson uses the long forms because they are easier to read. You will see the short forms often in older tutorials and scripts.
How to Create a JAR File in Java
Start with a small project of two classes in one package.
src/com/gocourse/greet/Greeter.java:
package com.gocourse.greet;
public class Greeter {
public static String greet(String name) {
return "Hello, " + name + "!";
}
}
src/com/gocourse/greet/Main.java:
package com.gocourse.greet;
public class Main {
public static void main(String[] args) {
String name = args.length > 0 ? args[0] : "Java learner";
System.out.println(Greeter.greet(name));
}
}
Compile the classes into out, then package that folder into a JAR:
javac -d out $(find src -name "*.java")
jar --create --file greet.jar -C out .
jar --list --file greet.jar
Output:
META-INF/
META-INF/MANIFEST.MF
com/
com/gocourse/
com/gocourse/greet/
com/gocourse/greet/Greeter.class
com/gocourse/greet/Main.class
How it works:
--create --file greet.jarmakes a new archive namedgreet.jar.-C out .means "change intooutand add everything there". The JAR then starts at the package root, soMain.classis stored ascom/gocourse/greet/Main.class.- Without
-C, writingjar --create --file greet.jar outwould storeout/com/gocourse/..., and the JVM could not find the classes by package name. - The
jartool always adds a defaultMETA-INF/MANIFEST.MF.
The short form with verbose output shows each file as it is added and compressed:
jar cvf greet.jar -C out .
Output:
added manifest
adding: com/(in = 0) (out= 0)(stored 0%)
adding: com/gocourse/(in = 0) (out= 0)(stored 0%)
adding: com/gocourse/greet/(in = 0) (out= 0)(stored 0%)
adding: com/gocourse/greet/Greeter.class(in = 715) (out= 400)(deflated 44%)
adding: com/gocourse/greet/Main.class(in = 595) (out= 375)(deflated 36%)
The exact byte counts depend on your JDK version.
Running Classes From a JAR With -cp
A JAR can be put on the classpath like a folder. You then name the main class yourself.
java -cp greet.jar com.gocourse.greet.Main Asha
Output:
Hello, Asha!
How it works:
-cp greet.jartells the JVM to look for classes inside the JAR.- The JVM converts
com.gocourse.greet.Mainto the entrycom/gocourse/greet/Main.classand loads it from the archive. Ashais passed tomainasargs[0].
Trying java -jar on this JAR fails, because it does not say which class to start:
java -jar greet.jar
Output:
no main manifest attribute, in greet.jar
Creating an Executable JAR File
An executable JAR has a Main-Class entry in its manifest. Add it with --main-class:
jar --create --file greet-app.jar --main-class com.gocourse.greet.Main -C out .
java -jar greet-app.jar Ravi
Output:
Hello, Ravi!
Look at the manifest the tool wrote. unzip -p prints one file from the archive:
unzip -p greet-app.jar META-INF/MANIFEST.MF
Output:
Manifest-Version: 1.0
Created-By: 21.0.12.1 (Ubuntu)
Main-Class: com.gocourse.greet.Main
How it works:
--main-class com.gocourse.greet.Main(short optione) writes theMain-Classattribute.java -jar greet-app.jarreads that attribute and startsmainin that class. You no longer need to remember the class name.Created-Byshows the JDK that built the JAR, so yours will differ. If you do not haveunzip, extract the JAR as shown later and openMETA-INF/MANIFEST.MFin a text editor.
Note: With
java -jar, the-cpoption and theCLASSPATHvariable are ignored. The JAR and its manifest decide the classpath. This surprises many beginners.
The JAR Manifest File Explained
The manifest is a plain-text file of Name: value lines. These are the attributes you will use most:
| Attribute | Example | Purpose |
|---|---|---|
Manifest-Version | 1.0 | Format version; added automatically |
Main-Class | com.gocourse.report.ReportApp | Class started by java -jar |
Class-Path | lib/gradelib-1.0.jar lib/other.jar | Extra JARs to load, relative to this JAR's location, separated by spaces |
Created-By | 21.0.12.1 (Ubuntu) | Tool that created the JAR; added automatically |
Implementation-Version | 1.0.0 | Version of your application, readable at runtime |
Automatic-Module-Name | com.gocourse.grades | Stable module name when the JAR is used on the module path |
To set attributes beyond Main-Class, write them in a text file and pass it with --manifest:
Main-Class: com.gocourse.report.ReportApp
Class-Path: lib/gradelib-1.0.jar
jar --create --file report-app.jar --manifest manifest.txt -C out .
How it works:
- The
jartool merges your lines with its defaults, soManifest-VersionandCreated-Byare still added. - The manifest file must end with a newline. If the last line has no line break, that last attribute is silently ignored.
- The full example at the end of this lesson uses this exact manifest.
Extracting and Updating a JAR File
Extract every entry into the current folder:
mkdir extracted && cd extracted
jar --extract --file ../greet-app.jar
find . -type f | sort
Output:
./META-INF/MANIFEST.MF
./com/gocourse/greet/Greeter.class
./com/gocourse/greet/Main.class
Add a new file to an existing JAR (run from the folder that holds greet-app.jar):
printf 'Version 1.0 of the greet app\n' > README.txt
jar --update --file greet-app.jar README.txt
jar --list --file greet-app.jar | tail -2
Output:
com/gocourse/greet/Main.class
README.txt
How it works:
--extractrecreates the folder structure from the archive. Extracting is a quick way to check what a JAR really contains, including its manifest.--updateaddsREADME.txt, or replaces it if an entry with that name already exists. To replace a class, use-C out com/gocourse/greet/Main.classso the stored path keeps its package folders.
Loading Resources From Inside a JAR
Files packed in a JAR are not normal files on disk, so new File("report.properties") cannot read them. Load them through the class loader with getResourceAsStream.
| Call | Where it looks |
|---|---|
MyClass.class.getResourceAsStream("report.properties") | Same package folder as MyClass |
MyClass.class.getResourceAsStream("/config/app.properties") | From the root of the classpath (leading /) |
ClassLoader.getSystemResourceAsStream("config/app.properties") | From the root of the classpath (no leading /) |
Properties config = new Properties();
try (InputStream in = ReportApp.class.getResourceAsStream("report.properties")) {
if (in == null) {
throw new IllegalStateException("report.properties not found in JAR");
}
config.load(in);
}
How it works:
getResourceAsStreamreturnsnullwhen the resource is missing, so always check before using it.- The same code works whether the classes run from a folder or from a JAR, because the class loader searches both the same way.
- The real-world example below packs this file into the JAR with a second
-Coption.
Reading a JAR File With Java Code
The java.util.jar package reads JARs from a program. JarFile opens the archive and gives you its manifest and entries.
import java.io.IOException;
import java.util.jar.Attributes;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
public class InspectJar {
public static void main(String[] args) throws IOException {
try (JarFile jar = new JarFile(args[0])) {
Manifest manifest = jar.getManifest();
Attributes main = manifest.getMainAttributes();
System.out.println("Main-Class: " + main.getValue(Attributes.Name.MAIN_CLASS));
jar.stream()
.filter(entry -> !entry.isDirectory())
.forEach(entry -> System.out.printf("%-35s %5d bytes%n", entry.getName(), entry.getSize()));
}
}
}
java InspectJar.java greet-app.jar
Output:
Main-Class: com.gocourse.greet.Main
META-INF/MANIFEST.MF 94 bytes
com/gocourse/greet/Greeter.class 715 bytes
com/gocourse/greet/Main.class 595 bytes
README.txt 29 bytes
How it works:
JarFileisAutoCloseable, so try-with-resources closes the archive.getMainAttributes()returns the top section of the manifest.Attributes.Name.MAIN_CLASSis the constant forMain-Class.jar.stream()returns a stream ofJarEntryobjects. Directories are skipped, andgetSize()is the uncompressed size.java InspectJar.javaruns the source file directly, which works for single-file programs since JDK 11.
Real-World Example: An App JAR That Uses a Library JAR
Real applications are usually split into a library JAR of reusable code and an app JAR that uses it. This example builds a grade library, an app that loads its settings from a resource, and a dist folder you can copy to any machine with Java installed.
marks/
├── gradelib/src/com/gocourse/grades/GradeCalculator.java
├── app/src/com/gocourse/report/ReportApp.java
├── app/resources/com/gocourse/report/report.properties
└── app/manifest.txt
gradelib/src/com/gocourse/grades/GradeCalculator.java:
package com.gocourse.grades;
public final class GradeCalculator {
private GradeCalculator() { }
public static double average(int... marks) {
int total = 0;
for (int mark : marks) {
total += mark;
}
return (double) total / marks.length;
}
public static String grade(double average, int passMark) {
if (average >= 90) return "A+";
if (average >= 75) return "A";
if (average >= 60) return "B";
if (average >= passMark) return "C";
return "FAIL";
}
}
app/resources/com/gocourse/report/report.properties:
report.title=GOCOURSE Java Batch - Term Report
pass.mark=40
app/src/com/gocourse/report/ReportApp.java:
package com.gocourse.report;
import com.gocourse.grades.GradeCalculator;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Properties;
public class ReportApp {
public static void main(String[] args) throws IOException {
Properties config = new Properties();
// Load report.properties from the same package folder inside the JAR
try (InputStream in = ReportApp.class.getResourceAsStream("report.properties")) {
if (in == null) {
throw new IllegalStateException("report.properties not found in JAR");
}
config.load(in);
}
int passMark = Integer.parseInt(config.getProperty("pass.mark"));
Map<String, int[]> students = new LinkedHashMap<>();
students.put("Asha", new int[]{95, 88, 91});
students.put("Ravi", new int[]{72, 64, 70});
students.put("Meena", new int[]{35, 42, 38});
System.out.println(config.getProperty("report.title"));
System.out.println("Pass mark: " + passMark);
students.forEach((name, marks) -> {
double average = GradeCalculator.average(marks);
System.out.printf("%-6s %6.2f %s%n", name, average, GradeCalculator.grade(average, passMark));
});
// Where did the classes come from?
System.out.println("App loaded from: " + location(ReportApp.class));
System.out.println("Library loaded from: " + location(GradeCalculator.class));
}
private static String location(Class<?> type) {
String path = type.getProtectionDomain().getCodeSource().getLocation().getPath();
return path.substring(path.lastIndexOf('/') + 1);
}
}
app/manifest.txt (ends with a newline):
Main-Class: com.gocourse.report.ReportApp
Class-Path: lib/gradelib-1.0.jar
Build both JARs from the marks folder:
# 1. Build the library JAR
javac -d gradelib/out $(find gradelib/src -name "*.java")
mkdir -p dist/lib
jar --create --file dist/lib/gradelib-1.0.jar -C gradelib/out .
# 2. Compile the app against the library, then package classes + resources
javac -d app/out -cp dist/lib/gradelib-1.0.jar $(find app/src -name "*.java")
jar --create --file dist/report-app.jar --manifest app/manifest.txt -C app/out . -C app/resources .
# 3. Run it
cd dist
java -jar report-app.jar
Output:
GOCOURSE Java Batch - Term Report
Pass mark: 40
Asha 91.33 A+
Ravi 68.67 B
Meena 38.33 FAIL
App loaded from: report-app.jar
Library loaded from: gradelib-1.0.jar
If lib/gradelib-1.0.jar is missing, the app starts but fails the first time it needs the library:
GOCOURSE Java Batch - Term Report
Pass mark: 40
Exception in thread "main" java.lang.NoClassDefFoundError: com/gocourse/grades/GradeCalculator
How it works:
- Two JARs, two jobs.
gradelib-1.0.jarcontains onlyGradeCalculator, so other apps can reuse it.report-app.jarcontains the app class and its resource. - Compile against the library.
-cp dist/lib/gradelib-1.0.jarletsjavacfindGradeCalculatorwhile compilingReportApp. - Two
-Coptions. The first adds compiled classes fromapp/out; the second addsreport.propertiesfromapp/resources. Both land incom/gocourse/report/, sogetResourceAsStream("report.properties")finds the file next to the class. Class-Pathin the manifest.java -jarreadslib/gradelib-1.0.jarrelative to the folder holdingreport-app.jar. Copy the wholedistfolder and the app keeps working.- Loaded on demand. The JVM loads
GradeCalculatoronly when it is first used. That is why the title prints before theNoClassDefFoundErrorwhen the library is missing. - The numbers. Asha averages
(95 + 88 + 91) / 3 = 91.33(A+), Ravi206 / 3 = 68.67(B), and Meena115 / 3 = 38.33, below the pass mark of 40.
Without the manifest, you can still run the same JARs by listing both on the classpath: java -cp "dist/report-app.jar:dist/lib/gradelib-1.0.jar" com.gocourse.report.ReportApp (use ; instead of : on Windows). Build tools such as Maven and Gradle automate all of these steps, and the Java Modules lesson shows how a JAR becomes a modular JAR. For the package layout used inside these JARs, revisit Create Package in Java.