Low Orbit Flux Logo 2 D

Java How to Create an Executable Jar File

We’re going to show you how to create an executable jar file and how to run it.

Quick Answer - These are the commands you are looking for:

javac HelloWorld.java
jar cfe HelloWorld.jar HelloWorld HelloWorld.class
java -jar HelloWorld.jar

The above commands use this source file:

class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }

Keep reading for more details. Note that the source file below is a bit different.

Creating a Jar File

Jar command parameters:

c create
f file
t list
e entry point
m manifest

First, create the project directory:

mkdir -p com/test/HelloWorld

Next, create a source file for the test program.

package com.test.HelloWorld; class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } }

Compile the source file:

javac com/test/HelloWorld/*.java

Build a jar file (non-executable):

jar cf HelloWorld.jar com/test/HelloWorld/*.class

Show the files inside a jar file with the following:

jar tf HelloWorld.jar

Build an executable Jar file. To do this you can explicitly specify the entry point like this:

jar cfe HelloWorld.jar com.test.HelloWorld.HelloWorld com/test/HelloWorld/*.class

You can also specify the entry point by passing a custom manifest file. Doing this will add whatever you specify in the file to the manifest in your jar. The manifest addition will look like this:

Main-Class: com.test.HelloWorld.HelloWorld

The manifest needs a newline at the end or it will be excluded silently.

You can specify your custom manifest addition like this:

jar cfm HelloWorld.jar com/test/HelloWorld/hello_world_manifest.txt com/test/HelloWorld/*.class

Running / Executing a Jar File

This will work if the main class was specified in the manifest.

java -jar HelloWorld.jar

We can also just run the main class directly if we specify that the jar should be on the class path using the “-cp” flags. This should work if we didn’t specify the main class in the manifest.

java -cp HelloWorld.jar:com/test/HelloWorld com.test.HelloWorld.HelloWorld

Updating a Jar File

You can update the contents of a jar file like this:

jar uf HelloWorld.jar com/test/HelloWorld/HelloWorld.class