15 Sep 2015
Run another application from Java
It is possible in java to run another application by calling exec method on Runtime object or using process builder class. This tutorial illustrates three examples, first will open calculator application and will close it after three seconds. The second example will run another Java process and read the output and error streams from that process. The third example is doing the similar job but implemented using ProcessBuilder class.
Example 1
package process; import java.io.IOException; public class OSProcess1 { public static void main(String[] args) { try { System.out.println("Opening calculator"); Runtime runTime = Runtime.getRuntime(); Process process = runTime.exec("calc"); try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("Closing calculator"); process.destroy(); } catch (IOException e) { e.printStackTrace(); } } }
Example 2
package process; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; public class OSProcess2 { public static void main(String[] args) { try { Runtime runTime = Runtime.getRuntime(); Process process = runTime.exec("java -classpath E:\\testing\\bin test.TestOutput"); InputStream inputStream = process.getInputStream(); InputStreamReader isr = new InputStreamReader(inputStream); InputStream errorStream = process.getErrorStream(); InputStreamReader esr = new InputStreamReader(errorStream); int n1; char[] c1 = new char[1024]; StringBuffer standardOutput = new StringBuffer(); while ((n1 = isr.read(c1)) > 0) { standardOutput.append(c1, 0, n1); } System.out.println("Standard Output: " + standardOutput.toString()); int n2; char[] c2 = new char[1024]; StringBuffer standardError = new StringBuffer(); while ((n2 = esr.read(c2)) > 0) { standardError.append(c2, 0, n2); } System.out.println("Standard Error: " + standardError.toString()); } catch (IOException e) { e.printStackTrace(); } } }
Example 3
package process; import java.io.*; public class OSProcess { public static void main(String[] args) throws IOException { if (args.length != 1) { System.err.println("Usage: java OSProcess"); System.exit(0); } // args[0] is the command that is run in a separate process //args[0] contains absolute path of application execute able file ProcessBuilder pb = new ProcessBuilder(args[0]); Process process = pb.start(); // obtain the input stream InputStream is = process.getInputStream(); InputStreamReader isr = new InputStreamReader(is); BufferedReader br = new BufferedReader(isr); // read the output of the process String line; while ((line = br.readLine()) != null) System.out.println(line); br.close(); } }
Reference :
Example three is taken from a book : “Operating System Concepts with Java”, Eight Edition