java.lang.ProcessBuilder

The ProcessBuilder class is one of the fundamental classes in creating operating system processes. This class is used to launch external program which means that you can call external script, program outside of the java program in order to accomplish desired task.

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.

ProcessBuilder Class Syntax

public final class ProcessBuilder
extends Object

ProcessBuilder Compatibility Version

Float Class is available since JDK 1.5

ProcessBuilder Basic Usage

One of the most basic use case of the ProcessBuilder is when you are required to run an external script from you java program. Let’s say for instance you need to run myprogram.bat in windows environment. First we have to create a new ProcessBuilder:

ProcessBuilder pb = new ProcessBuilder("C:/temp/myprogram.bat", "ryan"); );

The above code is basically telling that we want to run the batch file C:/temp/myprogram.bat with a first argument “ryan”.

Assume the following code on our batch file

echo hello %1

It means that we just wanted to have a print out on our console “hello ryan”. However since we only use an echo, we would not be able to know if the program runs successfully or not since there would be no display. In order to satisfy this, we will need to log the output to a file. Conveniently, there is a very simple method available with ProcessBuilder class:

ProcessBuilder pb = new ProcessBuilder("C:/temp/myprogram.bat", "ryan");
 File log = new File("C:/temp/log.txt");
 pb.redirectErrorStream(true);
 pb.redirectOutput(Redirect.appendTo(log));
 try {
 Process p = pb.start();
 } catch (IOException e) {
 // TODO Auto-generated catch block
 e.printStackTrace();
 }

Sample Output:

ProcessBuilder Basic Example

ProcessBuilder Basic Example

There are 2 constructor available with ProcessBuilder Class.

Constructor Description
ProcessBuilder(List<String> command) Constructs a process builder with the specified operating system program and arguments.
ProcessBuilder(String… command) Constructs a process builder with the specified operating system program and arguments.

We already discussed on how to use the Float(float value) in instantiating a Float object. So basically the other constructors usage is almost the same only in these cases we are accepting other primitive data type other than float.

ProcessBuilder Method Usage Examples

Modifier and Type Method and Description
List<String> command()
Returns this process builder’s operating system program and arguments.