Java The Complete Reference, Seventh Edition

(Greg DeLong) #1

408 Part II: The Java Library


To create a process usingProcessBuilder, simply create an instance ofProcessBuilder,
specifying the name of the program and any needed arguments. To begin execution of the
program, callstart( )on that instance. Here is an example that executes the Windows text
editornotepad. Notice that it specifies the name of the file to edit as an argument.

class PBDemo {
public static void main(String args[]) {

try {
ProcessBuilder proc =
new ProcessBuilder("notepad.exe", "testfile");
proc.start();
} catch (Exception e) {
System.out.println("Error executing notepad.");
}
}
}

Method Description
List<String> command( ) Returns a reference to aListthat contains the
name of the program and its arguments. Changes
to this list affect the invoking process.
ProcessBuilder command(List<String>args) Sets the name of the program and its arguments
to those specified byargs.Changes to this list
affect the invoking process. Returns a reference to
the invoking object.
ProcessBuilder command(String ...args) Sets the name of the program and its arguments
to those specified byargs.Returns a reference to
the invoking object.
File director y( ) Returns the current working director y of the invoking
object. This value will benullif the director y is the
same as that of the Java program that started the
process.
ProcessBuilder director y(Filedir) Sets the current working director y of the invoking
object. Returns a reference to the invoking object.
Map<String, String> environment( ) Returns the environmental variables associated
with the invoking object as key/value pairs.
boolean redirectErrorStream( ) Returnstrueif the standard error stream has been
redirected to the standard output stream. Returns
falseif the streams are separate.
ProcessBuilder
redirectErrorStream(booleanmerge)

Ifmergeistrue, then the standard error stream is
redirected to standard output. Ifmergeisfalse,
the streams are separated, which is the default
state. Returns a reference to the invoking object.
Process start( )
throws IOException

Begins the process specified by the invoking object.
In other words, it runs the specified program.

TABLE 16-12 The Methods Defined byProcessBuilder
Free download pdf