THE Java™ Programming Language, Fourth Edition

(Jeff_L) #1

throws IOException


The child process is given an initial working directory as specified by the path of dir. If dir is null, the
child process inherits the current working directory of the parentas specified by the system property
user.dir. The one- and two-argument forms of exec are equivalent to passing null for dir.


23.2.3. ProcessBuilder


The exec methods of Runtime are convenience methods that use the more general ProcessBuilder
class. ProcessBuilder encapsulates the three key attributes of an external process: the command, the
environment, and the current working directory. You can then start an external process with those attributes
by using the ProcessBuilder object's start methodwhich returns a Process object, just as exec
does.


ProcessBuilder has two constructors: One takes a sequence of String objects that represent the
command; the other a List that represents the command.


A fourth attribute you can control with ProcessBuilder, but not with exec, is whether the standard error
stream of the process is redirected to match the standard output stream of the process. Redirecting the error
stream merges all output into one stream, which makes it much easier to correlate when errors occur relative
to normal processing.


ProcessBuilder provides methods to query and set each of the four attributes. Each query method simply
names the attribute and returns its valuefor example, command returns the current command as a
List. The other query methods are


public Filedirectory()

Returns the working directory.

public Map<String, String>environment()

Returns a map containing all the environment variable settings

public booleanredirectErrorStream()

Returns true if the standard error stream should be redirected to the
standard output stream.

The setting methods have the same names as the query methods, but they take suitable arguments for the
attribute and return the ProcessBuilder object. However, there is no method to set the environment.
Instead, the map returned by environment can be modified directly and that will affect the environment of
any process subsequently started. Once a process has been started, any subsequent changes to the attributes of
the ProcessBuilder that started it have no effect on that process.


By returning the ProcessBuilder object different calls to set attributes can be chained together and
ultimately start invoked. For example, here is how we could rewrite the ls example, but with the error
stream redirected:


public String[] ls(String dir, String opts)
throws LSFailedException
{
try {

Free download pdf