This class is used to create operating system processes.
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.
startPipeline method can be invoked to create a pipeline of new processes that send the output of each process directly to the next process. Each process has the attributes of its respective ProcessBuilder.
Each process builder manages these process attributes:
Modifying a process builder's attributes will affect processes subsequently started by that object's
start() method, but will never affect previously started processes or the Java process itself.
Most error checking is performed by the
start() method. It is possible to modify the state of an object so that
start() will fail. For example, setting the command attribute to an empty list will not throw an exception unless
start() is invoked.
Note that this class is not synchronized. If multiple threads access a
ProcessBuilder instance concurrently, and at least one of the threads modifies one of the attributes structurally, it must be synchronized externally.
Starting a new process which uses the default working directory and environment is easy:
Process p = new ProcessBuilder("myCommand", "myArg").start();
Here is an example that starts a process with a modified working directory and environment, and redirects standard output and error to be appended to a log file:
ProcessBuilder pb =
new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();
env.put("VAR2", env.get("VAR1") + "suffix");
File log = new File("log");
Process p = pb.start();
assert pb.redirectInput() == Redirect.PIPE;
assert pb.redirectOutput().file() == log;
assert p.getInputStream().read() == -1;
To start a process with an explicit set of environment variables, first call
Map.clear() before adding environment variables.
Unless otherwise noted, passing a
null argument to a constructor or method in this class will cause a
NullPointerException to be thrown.