Core Java

Java Execute JAR File Example

A JAR (Java Archive) file is a packaged collection of Java classes and resources that can be executed as a standalone application if it contains a MANIFEST.MF file specifying the main class. Let us delve into understanding how Java executes a JAR file efficiently.

1. What is a JAR?

A JAR (Java ARchive) file is a package file format used in Java to aggregate multiple Java class files, associated metadata, and resources (such as images and configuration files) into a single compressed file. JAR files use the .jar extension and are based on the ZIP format. They are commonly used for distributing Java applications, libraries, and plug-ins. By packaging all required files into one archive, JAR files simplify deployment and improve efficiency.

JAR files can be executed if they contain a valid MANIFEST.MF file specifying the main class. Users can run an executable JAR file using the Java Runtime Environment (JRE) with the command: java -jar filename.jar. Additionally, developers can sign JAR files for security, ensuring authenticity and integrity.

2. Run a JAR File

An executable JAR contains a MANIFEST.MF file that specifies the main class. The standard way to run an executable JAR from Java is by using the ProcessBuilder or Runtime.exec().

2.1 Comparison

FeatureProcessBuilderRuntime.exec()
FlexibilityMore flexible, allows modification of environment variables and working directory.Less flexible, does not provide direct control over environment variables.
Output RedirectionSupports I/O redirection using inheritIO() or streams.Requires handling of output and error streams manually.
Ease of UseMore structured API, recommended for managing external processes.Less structured, requires more handling for advanced use cases.
Command ExecutionAllows specifying commands as a list of strings, avoiding issues with spaces.Requires specifying commands as a single string, which may lead to issues with spaces.
Recommended UsagePreferred for executing and managing external processes in modern Java applications.Used for simple command execution but less recommended for complex tasks.

As Runtime.exec() provides limited flexibility, we will use ProcessBuilder for a clearer understanding of the examples.

2.2 Executing an Executable JAR

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
import java.io.IOException;
 
public class RunJarExample {
  public static void main(String[] args) {
    try {
      // Define the command to run the JAR file
      ProcessBuilder processBuilder = new ProcessBuilder("java", "-jar", "example.jar");
      processBuilder.inheritIO(); // Redirect output to console
      Process process = processBuilder.start();
 
      // Wait for the process to finish
      int exitCode = process.waitFor();
      System.out.println("JAR execution completed with exit code: " + exitCode);
    } catch (IOException | InterruptedException e) {
      e.printStackTrace();
    }
  }
}

The example.jar file is beyond the scope of this article, so we have not provided a demonstration for it. However, it contains a simple “Hello, World!” program.

2.2.1 Code Explanation and Output

The given Java program demonstrates how to execute a JAR file programmatically using the ProcessBuilder class. It constructs a process to run the command java -jar example.jar, where “example.jar” represents the JAR file to be executed. The inheritIO() method is used to redirect the JAR’s output to the console, ensuring visibility of its execution results. The process is then started using processBuilder.start(), and the program waits for its completion using process.waitFor(). Finally, the exit code of the executed JAR is printed.

1
JAR execution completed with exit code: 0

If an IOException or InterruptedException occurs, the stack trace is displayed for debugging.

2.3 Executing a Non-executable Jar File

A non-executable JAR does not contain a main class in its manifest. To execute a class inside it, we must specify the class name explicitly.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
import java.io.IOException;
 
public class RunNonExecutableJar {
  public static void main(String[] args) {
    try {
      // Running a specific class inside the JAR
      ProcessBuilder processBuilder = new ProcessBuilder("java", "-cp", "example.jar", "com.example.MainClass");
      processBuilder.inheritIO();
      Process process = processBuilder.start();
 
      int exitCode = process.waitFor();
      System.out.println("Non-executable JAR execution completed with exit code: " + exitCode);
    } catch (IOException | InterruptedException e) {
      e.printStackTrace();
    }
  }
}

The example.jar and com.example.MainClass files are beyond the scope of this article, so we have not provided a demonstration for it.

2.3.1 Code Explanation and Output

The given Java program demonstrates how to run a specific class inside a non-executable JAR file using the ProcessBuilder class. Unlike an executable JAR, which contains a predefined Main-Class in its manifest, this approach requires specifying the classpath using the -cp option and explicitly mentioning the class to be executed (e.g., com.example.MainClass). The inheritIO() method ensures that the JAR’s output is redirected to the console. The process is then started with processBuilder.start(), and the program waits for its completion using process.waitFor(). Finally, the exit code of the execution is printed.

1
Non-executable JAR execution completed with exit code: 0

If any IOException or InterruptedException occurs, the stack trace is displayed.

3. Conclusion

Executing a JAR file from a Java program can be done using ProcessBuilder or Runtime.exec(). Executable JARs can be run directly with the -jar flag, while non-executable JARs require specifying a particular class to run. These approaches are useful for automation and programmatically executing Java applications.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest


This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button