Explain Codes LogoExplain Codes Logo

How to run a JAR file

java
manifest
classpath
java-8
Nikita BarsukovbyNikita Barsukov·Sep 10, 2024
TLDR

To execute a JAR file, use the straightforward command:

java -jar awesome-app.jar

This requires Java being installed and java being set in your system's PATH.

Notably, this instruction assumes that a Main-Class attribute, which serves as the application's entry point, is specified in the JAR's manifest file. The manifest file should end with a newline to parse correctly. Here's how to package your compiled .class files into an executable JAR:

jar cfm awesome-app.jar manifest.mf ClassName.class

Ensure the class name defined in Main-Class is your application's entry point and is properly referenced in the manifest.

Nailing the fundamentals

Before proceeding, confirm Java JDK installation. Compile your .java files using:

javac MyClass.java

The process: From source code to JAR

Follow these steps to create a JAR file, with the main class set as the entry point:

  1. Craft your manifest.mf—define the main class appropriately:

    Main-Class: MyMainClass
  2. The manifest must always end with a newline character. It's not pedantic—it's standard.

  3. Bundle the classes in a JAR:

    jar cfm awesome-app.jar manifest.mf MyMainClass.class

Launch and troubleshoot

To execute the JAR, the typical command is:

java -jar awesome-app.jar

Encountering trouble? Verify your manifest file is nested in the META-INF directory and the package structure aligns with the class definitions.

Deciphering the Manifest

  • Check for a valid manifest version with Manifest-Version: 1.0.
  • Ensure the entry point in the Main-Class definition matches the actual class name.

Get the nitty-gritty with the Command Line

Run your JAR in the command line rather than double-clicking for extended error logs—enjoy the bittersweet symphony of bug fixing!

Alternative launching processes

Alternate methods to run your JAR include:

  • Using classpath: java -cp awesome-app.jar your.package.MainClass.
  • If the ZIP utility was a person, it would be your new best friend—employ it to modify the manifest post-creation.

Behold, the non-executable JARs

For non-executable JARs, you'll have to call the main class directly:

java -classpath awesome-app.jar your.package.MainClass