ProcessBuilder

How to run external JAVA program by using ProcessBuilder

Posted on

java-logojava.lang.ProcessBuilder was introduced in Java 1.5 version, is used to create an Operating System Process. see Java API

Before going on example section, see ProcessBuilder attributes:-

 

Each ProcessBuilder instance manages a collection of process attributes. The start() method creates a new Process instance with those attributes. The start() method can be invoked repeatedly from the same instance to create new subprocesses with identical or related attributes.

Each process builder manages these process attributes:

  • a command, a list of strings which signifies the external program file to be invoked and its arguments, if any. Which string lists represent a valid operating system command is system-dependent. For example, it is common for each conceptual argument to be an element in this list, but there are operating systems where programs are expected to tokenize command line strings themselves – on such a system a Java implementation might require commands to contain exactly two elements.
  • an environment, which is a system-dependent mapping from variables to values. The initial value is a copy of the environment of the current process (see System.getenv()).
  • a working directory. The default value is the current working directory of the current process, usually the directory named by the system property user.dir.
  • a source of standard input. By default, the subprocess reads input from a pipe. Java code can access this pipe via the output stream returned by Process.getOutputStream(). However, standard input may be redirected to another source using redirectInput. In this case, Process.getOutputStream() will return a null output stream, for which:
    • the write methods always throw IOException
    • the close method does nothing
  • a destination for standard output and standard error. By default, the subprocess writes standard output and standard error to pipes. Java code can access these pipes via the input streams returned by Process.getInputStream() and Process.getErrorStream(). However, standard output and standard error may be redirected to other destinations using redirectOutput andredirectError. In this case, Process.getInputStream() and/or Process.getErrorStream() will return a null input stream, for which:
    • the read methods always return -1
    • the available method always returns 0
    • the close method does nothing
  • a redirectErrorStream property. Initially, this property is false, meaning that the standard output and error output of a subprocess are sent to two separate streams, which can be accessed using the Process.getInputStream() and Process.getErrorStream() methods.If the value is set to true, then:
    • standard error is merged with the standard output and always sent to the same destination (this makes it easier to correlate error messages with the corresponding output)
    • the common destination of standard error and standard output can be redirected using redirectOutput
    • any redirection set by the redirectError method is ignored when creating a subprocess
    • the stream returned from Process.getErrorStream() will always be a null input stream

Following example demonstrate how to run external Java program, Same way we can run any external program which must be set in OS environment.

Before running this program on your machine, make sure that JAVA_HOME must be set in your OS environment.


package com.itexpert.exam;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

public class JavaProcessBuilder {
/**
* Provide absolute JAVA file path
*/
private static final String JAVA_FILE_LOCATION = "D:\\Test.java";

public static void main(String args[]) throws IOException{
String command[] = {"javac",JAVA_FILE_LOCATION};
ProcessBuilder processBuilder = new ProcessBuilder(command);

Process process = processBuilder.start();
/**
* Check if any errors or compilation errors encounter then print on Console.
*/

if( process.getErrorStream().read() != -1 ){
print("Compilation Errors",process.getErrorStream());
}
/**
* Check if javac process execute successfully or Not
* 0 - successful
*/
if( process.exitValue() == 0 ){
process = new ProcessBuilder(new String[]{"java","-cp","d:\\","Test"}).start();
/** Check if RuntimeException or Errors encounter during execution then print errors on console
* Otherwise print Output
*/
if( process.getErrorStream().read() != -1 ){
print("Errors ",process.getErrorStream());
}
else{
print("Output ",process.getInputStream());
}

}
}

private static void print(String status,InputStream input) throws IOException{
BufferedReader in = new BufferedReader(new InputStreamReader(input));
System.out.println("************* "+status+"***********************");
String line = null;
while((line = in.readLine()) != null ){
System.out.println(line);
}
in.close();
}

}

External Java Program source code below:-


public class Test {
public static void main(String args[]){
System.out.println("Hello, How are you !!!");
}
}


Output if Compilation done successfully


************* Output ***********************
Hello, How are you !!!

Suppose, if we pass incorrect file “Test1” through command[] object which does not exist in your given path then-


************* Compilation Errors***********************
avac: file not found: D:\Test1.java
Usage: javac 
use -help for a list of possible options

Suppose, if any compilation errors exist in Java file then-


************* Compilation Errors***********************
:\Test.java:3: error: cannot find symbol
		System.out.printlna("Hello, How are you !!!");
		          ^
  symbol:   method printlna(String)
  location: variable out of type PrintStream
1 error

Thanks !!

Advertisements