JAR File in Java: Create, Run and Inspect JAR Files

Su Suriya Ravichandran Updated 18 Nov 2026
11 min read ·Lesson 228 of 306

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
PartPurpose
Package folders (com/gocourse/greet/)Let the JVM find classes by their fully qualified names
META-INF/MANIFEST.MFKey-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 jar tool 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.

TaskLong formShort form
Create a JARjar --create --file app.jar ...jar cf app.jar ...
List contentsjar --list --file app.jarjar tf app.jar
Extract contentsjar --extract --file app.jarjar xf app.jar
Add or replace filesjar --update --file app.jar ...jar uf app.jar ...
Set the entry point--main-class com.x.Maine (as in jar cfe app.jar com.x.Main ...)
Use a manifest file--manifest manifest.txtm (as in jar cfm app.jar manifest.txt ...)
Change directory first-C out .-C out .
Show each file added--verbosev

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.jar makes a new archive named greet.jar.
  • -C out . means "change into out and add everything there". The JAR then starts at the package root, so Main.class is stored as com/gocourse/greet/Main.class.
  • Without -C, writing jar --create --file greet.jar out would store out/com/gocourse/..., and the JVM could not find the classes by package name.
  • The jar tool always adds a default META-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.jar tells the JVM to look for classes inside the JAR.
  • The JVM converts com.gocourse.greet.Main to the entry com/gocourse/greet/Main.class and loads it from the archive.
  • Asha is passed to main as args[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 option e) writes the Main-Class attribute.
  • java -jar greet-app.jar reads that attribute and starts main in that class. You no longer need to remember the class name.
  • Created-By shows the JDK that built the JAR, so yours will differ. If you do not have unzip, extract the JAR as shown later and open META-INF/MANIFEST.MF in a text editor.

Note: With java -jar, the -cp option and the CLASSPATH variable 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:

AttributeExamplePurpose
Manifest-Version1.0Format version; added automatically
Main-Classcom.gocourse.report.ReportAppClass started by java -jar
Class-Pathlib/gradelib-1.0.jar lib/other.jarExtra JARs to load, relative to this JAR's location, separated by spaces
Created-By21.0.12.1 (Ubuntu)Tool that created the JAR; added automatically
Implementation-Version1.0.0Version of your application, readable at runtime
Automatic-Module-Namecom.gocourse.gradesStable 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 jar tool merges your lines with its defaults, so Manifest-Version and Created-By are 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:

  • --extract recreates the folder structure from the archive. Extracting is a quick way to check what a JAR really contains, including its manifest.
  • --update adds README.txt, or replaces it if an entry with that name already exists. To replace a class, use -C out com/gocourse/greet/Main.class so 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.

CallWhere 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:

  • getResourceAsStream returns null when 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 -C option.

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:

  • JarFile is AutoCloseable, so try-with-resources closes the archive.
  • getMainAttributes() returns the top section of the manifest. Attributes.Name.MAIN_CLASS is the constant for Main-Class.
  • jar.stream() returns a stream of JarEntry objects. Directories are skipped, and getSize() is the uncompressed size.
  • java InspectJar.java runs 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:

  1. Two JARs, two jobs. gradelib-1.0.jar contains only GradeCalculator, so other apps can reuse it. report-app.jar contains the app class and its resource.
  2. Compile against the library. -cp dist/lib/gradelib-1.0.jar lets javac find GradeCalculator while compiling ReportApp.
  3. Two -C options. The first adds compiled classes from app/out; the second adds report.properties from app/resources. Both land in com/gocourse/report/, so getResourceAsStream("report.properties") finds the file next to the class.
  4. Class-Path in the manifest. java -jar reads lib/gradelib-1.0.jar relative to the folder holding report-app.jar. Copy the whole dist folder and the app keeps working.
  5. Loaded on demand. The JVM loads GradeCalculator only when it is first used. That is why the title prints before the NoClassDefFoundError when the library is missing.
  6. The numbers. Asha averages (95 + 88 + 91) / 3 = 91.33 (A+), Ravi 206 / 3 = 68.67 (B), and Meena 115 / 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.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about JAR File in Java: Create, Run and Inspect JAR Files and get answers drawn from it.

Signed-in readers only.