Sample code to execute jar file from Java Program.
Pre-requisite
1. Need to have executable jar file.
2. Copy the code in your workspace and Run the code.
package com.test.reusable.enterprise.service;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.commons.lang.exception.ExceptionUtils;
public class ExecuteJarFile {
public static void main(String[] args) {
try {
//Method1 to Execute Jar file From Java Program
ProcessBuilder pb = new ProcessBuilder("java", "-jar", "HelloWorld.jar"); // command to execute jar file with fileName.jar
pb.redirectErrorStream(true);
pb.directory(new File("C:/www/")); // Directory path where your jar file is placed.
Process p = pb.start();
InputStream is = p.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
System.out.println("===== Method 1 output =====");
for (String line = br.readLine(); line != null; line = br.readLine()) {
System.out.println( line ); // Or just ignore it
}
p.waitFor();
//Method2 to Execute Jar file From Java Program
Runtime re = Runtime.getRuntime();
BufferedReader output = null;
try{
Process cmd = re.exec("java -jar C:/www/HelloWorld.jar"); // command to execute jar file with complete path
output = new BufferedReader(new InputStreamReader(cmd.getInputStream()));
} catch (IOException ioe){
ioe.printStackTrace();
}
String resultOutput = output.readLine();
System.out.println("===== Method 2 output =====");
System.out.println("resultOutput :: "+resultOutput);
} catch (Exception e2) {
String fullStackTrace = ExceptionUtils.getFullStackTrace(e2);
System.out.println("Caught Exception :: "+fullStackTrace);
}
}
}
=========== Output ===========
I hope that above given example gives you a better understanding of executing jar file from java program.
Comments
Post a Comment