Class ProcessBuilder

java.lang.Object
java.lang.ProcessBuilder

public final classProcessBuilderextendsObject
This class is used to create operating system processes.

EachProcessBuilder instance manages a collectionof process attributes. Thestart() method creates a newProcess instance with those attributes. Thestart() method can be invoked repeatedly from the same instanceto create new subprocesses with identical or related attributes.

ThestartPipeline method can be invoked to createa pipeline of new processes that send the output of each processdirectly to the next process. Each process has the attributes ofits respective ProcessBuilder.

Each process builder manages these process attributes:

  • acommand, a list of strings which signifies theexternal program file to be invoked and its arguments, if any.Which string lists represent a valid operating system command issystem-dependent. For example, it is common for each conceptualargument to be an element in this list, but there are operatingsystems where programs are expected to tokenize command linestrings themselves - on such a system a Java implementation mightrequire commands to contain exactly two elements.
  • anenvironment, which is a system-dependent mapping fromvariables tovalues. The initial value is a copy ofthe environment of the current process (seeSystem.getenv()).
  • aworking directory. The default value is the currentworking directory of the current process, usually the directorynamed by the system propertyuser.dir.
  • a source ofstandard input.By default, the subprocess reads input from a pipe. Java codecan access this pipe via the output stream returned byProcess.getOutputStream(). However, standard input maybe redirected to another source usingredirectInput.In this case,Process.getOutputStream() will return anull output stream, for which:
    • thewrite methods alwaysthrowIOException
    • theclose method does nothing
  • a destination forstandard outputandstandard error. By default, the subprocess writes standardoutput and standard error to pipes. Java code can access these pipesvia the input streams returned byProcess.getInputStream() andProcess.getErrorStream(). However, standard output andstandard error may be redirected to other destinations usingredirectOutput andredirectError.In this case,Process.getInputStream() and/orProcess.getErrorStream() will return anull inputstream, for which:
    • theread methods always return-1
    • theavailable method always returns0
    • theclose method does nothing
  • aredirectErrorStream property. Initially, this propertyisfalse, meaning that the standard output and erroroutput of a subprocess are sent to two separate streams, which canbe accessed using theProcess.getInputStream() andProcess.getErrorStream() methods.

    If the value is set totrue, then:

    • standard error is merged with the standard output and always sentto the same destination (this makes it easier to correlate errormessages with the corresponding output)
    • the common destination of standard error and standard output can beredirected usingredirectOutput
    • any redirection set by theredirectErrormethod is ignored when creating a subprocess
    • the stream returned fromProcess.getErrorStream() willalways be anull input stream

Modifying a process builder's attributes will affect processessubsequently started by that object'sstart() method, butwill never affect previously started processes or the Java processitself.

Most error checking is performed by thestart() method.It is possible to modify the state of an object so thatstart() will fail. For example, setting the command attribute toan empty list will not throw an exception unlessstart()is invoked.

Note that this class is not synchronized.If multiple threads access aProcessBuilder instanceconcurrently, and at least one of the threads modifies one of theattributes structurally, itmust be synchronized externally.

Starting a new process which uses the default working directoryand environment is easy:

Process p = new ProcessBuilder("myCommand", "myArg").start();

Here is an example that starts a process with a modified workingdirectory and environment, and redirects standard output and errorto be appended to a log file:

    ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");    Map<String, String> env = pb.environment();    env.put("VAR1", "myValue");    env.remove("OTHERVAR");    env.put("VAR2", env.get("VAR1") + "suffix");    pb.directory(new File("myDir"));    File log = new File("log");    pb.redirectErrorStream(true);    pb.redirectOutput(Redirect.appendTo(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 environmentvariables, first callMap.clear()before adding environment variables.

Unless otherwise noted, passing anull argument to a constructoror method in this class will cause aNullPointerException to bethrown.

Since:
1.5
  • Constructor Details

    • ProcessBuilder

      public ProcessBuilder(List<String> command)
      Constructs a process builder with the specified operatingsystem program and arguments. This constructor doesnotmake a copy of thecommand list. Subsequentupdates to the list will be reflected in the state of theprocess builder. It is not checked whethercommand corresponds to a valid operating systemcommand.
      Parameters:
      command - the list containing the program and its arguments
    • ProcessBuilder

      public ProcessBuilder(String... command)
      Constructs a process builder with the specified operatingsystem program and arguments. This is a convenienceconstructor that sets the process builder's command to a stringlist containing the same strings as thecommandarray, in the same order. It is not checked whethercommand corresponds to a valid operating systemcommand.
      Parameters:
      command - a string array containing the program and its arguments
  • Method Details

    • command

      public ProcessBuilder command(List<String> command)
      Sets this process builder's operating system program andarguments. This method doesnot make a copy of thecommand list. Subsequent updates to the list willbe reflected in the state of the process builder. It is notchecked whethercommand corresponds to a validoperating system command.
      Parameters:
      command - the list containing the program and its arguments
      Returns:
      this process builder
    • command

      public ProcessBuilder command(String... command)
      Sets this process builder's operating system program andarguments. This is a convenience method that sets the commandto a string list containing the same strings as thecommand array, in the same order. It is notchecked whethercommand corresponds to a validoperating system command.
      Parameters:
      command - a string array containing the program and its arguments
      Returns:
      this process builder
    • command

      public List<String> command()
      Returns this process builder's operating system program andarguments. The returned list isnot a copy. Subsequentupdates to the list will be reflected in the state of thisprocess builder.
      Returns:
      this process builder's program and its arguments
    • environment

      public Map<String,String> environment()
      Returns a string map view of this process builder's environment.Whenever a process builder is created, the environment isinitialized to a copy of the current process environment (seeSystem.getenv()). Subprocesses subsequently started bythis object'sstart() method will use this map astheir environment.

      The returned object may be modified using ordinaryMap operations. These modifications will bevisible to subprocesses started via thestart()method. TwoProcessBuilder instances alwayscontain independent process environments, so changes to thereturned map will never be reflected in any otherProcessBuilder instance or the values returned bySystem.getenv.

      If the system does not support environment variables, anempty map is returned.

      The returned map does not permit null keys or values.Attempting to insert or query the presence of a null key orvalue will throw aNullPointerException.Attempting to query the presence of a key or value which is notof typeString will throw aClassCastException.

      The behavior of the returned map is system-dependent. Asystem may not allow modifications to environment variables ormay forbid certain variable names or values. For this reason,attempts to modify the map may fail withUnsupportedOperationException orIllegalArgumentExceptionif the modification is not permitted by the operating system.

      Since the external format of environment variable names andvalues is system-dependent, there may not be a one-to-onemapping between them and Java's Unicode strings. Nevertheless,the map is implemented in such a way that environment variableswhich are not modified by Java code will have an unmodifiednative representation in the subprocess.

      The returned map and its collection views may not obey thegeneral contract of theObject.equals(Object) andObject.hashCode() methods.

      The returned map is typically case-sensitive on all platforms.

      When passing information to a Java subprocess,system propertiesare generally preferred over environment variables.

      Returns:
      this process builder's environment
      See Also:
    • directory

      public File directory()
      Returns this process builder's working directory.Subprocesses subsequently started by this object'sstart() method will use this as their working directory.The returned value may benull -- this means to usethe working directory of the current Java process, usually thedirectory named by the system propertyuser.dir,as the working directory of the child process.
      Returns:
      this process builder's working directory
    • directory

      public ProcessBuilder directory(File directory)
      Sets this process builder's working directory.Subprocesses subsequently started by this object'sstart() method will use this as their working directory.The argument may benull -- this means to use theworking directory of the current Java process, usually thedirectory named by the system propertyuser.dir,as the working directory of the child process.
      Parameters:
      directory - the new working directory
      Returns:
      this process builder
    • redirectInput

      public ProcessBuilder redirectInput(ProcessBuilder.Redirect source)
      Sets this process builder's standard input source.Subprocesses subsequently started by this object'sstart()method obtain their standard input from this source.

      If the source isRedirect.PIPE(the initial value), then the standard input of asubprocess can be written to using the output streamreturned byProcess.getOutputStream().If the source is set to any other value, thenProcess.getOutputStream() will return anull output stream.

      Parameters:
      source - the new standard input source
      Returns:
      this process builder
      Throws:
      IllegalArgumentException - if the redirect does not correspond to a valid source of data, that is, has typeWRITE orAPPEND
      Since:
      1.7
    • redirectOutput

      public ProcessBuilder redirectOutput(ProcessBuilder.Redirect destination)
      Sets this process builder's standard output destination.Subprocesses subsequently started by this object'sstart()method send their standard output to this destination.

      If the destination isRedirect.PIPE(the initial value), then the standard output of a subprocesscan be read using the input stream returned byProcess.getInputStream().If the destination is set to any other value, thenProcess.getInputStream() will return anull input stream.

      Parameters:
      destination - the new standard output destination
      Returns:
      this process builder
      Throws:
      IllegalArgumentException - if the redirect does not correspond to a valid destination of data, that is, has typeREAD
      Since:
      1.7
    • redirectError

      public ProcessBuilder redirectError(ProcessBuilder.Redirect destination)
      Sets this process builder's standard error destination.Subprocesses subsequently started by this object'sstart()method send their standard error to this destination.

      If the destination isRedirect.PIPE(the initial value), then the error output of a subprocesscan be read using the input stream returned byProcess.getErrorStream().If the destination is set to any other value, thenProcess.getErrorStream() will return anull input stream.

      If theredirectErrorStreamattribute has been settrue, then the redirection setby this method has no effect.

      Parameters:
      destination - the new standard error destination
      Returns:
      this process builder
      Throws:
      IllegalArgumentException - if the redirect does not correspond to a valid destination of data, that is, has typeREAD
      Since:
      1.7
    • redirectInput

      public ProcessBuilder redirectInput(File file)
      Sets this process builder's standard input source to a file.

      This is a convenience method. An invocation of the formredirectInput(file)behaves in exactly the same way as the invocationredirectInput(Redirect.from(file)).

      Parameters:
      file - the new standard input source
      Returns:
      this process builder
      Since:
      1.7
    • redirectOutput

      public ProcessBuilder redirectOutput(File file)
      Sets this process builder's standard output destination to a file.

      This is a convenience method. An invocation of the formredirectOutput(file)behaves in exactly the same way as the invocationredirectOutput(Redirect.to(file)).

      Parameters:
      file - the new standard output destination
      Returns:
      this process builder
      Since:
      1.7
    • redirectError

      public ProcessBuilder redirectError(File file)
      Sets this process builder's standard error destination to a file.

      This is a convenience method. An invocation of the formredirectError(file)behaves in exactly the same way as the invocationredirectError(Redirect.to(file)).

      Parameters:
      file - the new standard error destination
      Returns:
      this process builder
      Since:
      1.7
    • redirectInput

      public ProcessBuilder.Redirect redirectInput()
      Returns this process builder's standard input source.Subprocesses subsequently started by this object'sstart()method obtain their standard input from this source.The initial value isRedirect.PIPE.
      Returns:
      this process builder's standard input source
      Since:
      1.7
    • redirectOutput

      public ProcessBuilder.Redirect redirectOutput()
      Returns this process builder's standard output destination.Subprocesses subsequently started by this object'sstart()method redirect their standard output to this destination.The initial value isRedirect.PIPE.
      Returns:
      this process builder's standard output destination
      Since:
      1.7
    • redirectError

      public ProcessBuilder.Redirect redirectError()
      Returns this process builder's standard error destination.Subprocesses subsequently started by this object'sstart()method redirect their standard error to this destination.The initial value isRedirect.PIPE.
      Returns:
      this process builder's standard error destination
      Since:
      1.7
    • inheritIO

      public ProcessBuilder inheritIO()
      Sets the source and destination for subprocess standard I/Oto be the same as those of the current Java process.

      This is a convenience method. An invocation of the form

           pb.inheritIO()
      behaves in exactly the same way as the invocation
           pb.redirectInput(Redirect.INHERIT)         .redirectOutput(Redirect.INHERIT)         .redirectError(Redirect.INHERIT)
      This gives behavior equivalent to most operating systemcommand interpreters, or the standard C library functionsystem().

      Returns:
      this process builder
      Since:
      1.7
    • redirectErrorStream

      public boolean redirectErrorStream()
      Tells whether this process builder merges standard error andstandard output.

      If this property istrue, then any error outputgenerated by subprocesses subsequently started by this object'sstart() method will be merged with the standardoutput, so that both can be read using theProcess.getInputStream() method. This makes it easierto correlate error messages with the corresponding output.The initial value isfalse.

      Returns:
      this process builder'sredirectErrorStream property
    • redirectErrorStream

      public ProcessBuilder redirectErrorStream(boolean redirectErrorStream)
      Sets this process builder'sredirectErrorStream property.

      If this property istrue, then any error outputgenerated by subprocesses subsequently started by this object'sstart() method will be merged with the standardoutput, so that both can be read using theProcess.getInputStream() method. This makes it easierto correlate error messages with the corresponding output.The initial value isfalse.

      Parameters:
      redirectErrorStream - the new property value
      Returns:
      this process builder
    • start

      public Process start() throwsIOException
      Starts a new process using the attributes of this process builder.

      The new process willinvoke the command and arguments given bycommand(),in a working directory as given bydirectory(),with a process environment as given byenvironment().

      This method checks that the command is a valid operatingsystem command. Which commands are valid is system-dependent,but at the very least the command must be a non-empty list ofnon-null strings.

      A minimal set of system dependent environment variables maybe required to start a process on some operating systems.As a result, the subprocess may inherit additional environment variablesettings beyond those in the process builder'senvironment().The minimal set of system dependent environment variablesmay override the values provided in the environment.

      Starting an operating system process is highly system-dependent.Among the many things that can go wrong are:

      • The operating system program file was not found.
      • Access to the program file was denied.
      • The working directory does not exist.
      • Invalid character in command argument, such as NUL.

      In such cases an exception will be thrown. The exact natureof the exception is system-dependent, but it will always be asubclass ofIOException.

      If the operating system does not support the creation ofprocesses, anUnsupportedOperationException will be thrown.

      Subsequent modifications to this process builder will notaffect the returnedProcess.

      Implementation Note:
      In the reference implementation, logging of the command, arguments, directory,stack trace, and process id can be enabled.The logged information may contain sensitive security information and the potential exposureof the information should be carefully reviewed.Logging of the information is enabled when the logging level of thesystem logger namedjava.lang.ProcessBuilderisLevel.DEBUG orLevel.TRACE.When enabled forLevel.DEBUG only the process id, directory, command, and stack traceare logged.When enabled forLevel.TRACE the arguments are included with the process id,directory, command, and stack trace.
      Returns:
      a newProcess object for managing the subprocess
      Throws:
      NullPointerException - if an element of the command list is null
      IndexOutOfBoundsException - if the command is an empty list (has size0)
      UnsupportedOperationException - If the operating system does not support the creation of processes.
      IOException - if an I/O error occurs
      See Also:
    • startPipeline

      public static List<Process> startPipeline(List<ProcessBuilder> builders) throwsIOException
      Starts a Process for each ProcessBuilder, creating a pipeline ofprocesses linked by their standard output and standard input streams.The attributes of each ProcessBuilder are used to start the respectiveprocess except that as each process is started, its standard outputis directed to the standard input of the next. The redirects for standardinput of the first process and standard output of the last process areinitialized using the redirect settings of the respective ProcessBuilder.All otherProcessBuilder redirects should beRedirect.PIPE.

      All input and output streams between the intermediate processes arenot accessible.Thestandard input of all processesexcept the first process arenull output streamsThestandard output of all processesexcept the last process arenull input streams.

      TheredirectErrorStream() of each ProcessBuilder applies to therespective process. If set totrue, the error stream is writtento the same stream as standard output.

      If starting any of the processes throws an Exception, all processesare forcibly destroyed.

      ThestartPipeline method performs the same checks oneach ProcessBuilder as does thestart() method. Each new processinvokes the command and arguments given by the respective process builder'scommand(), in a working directory as given by itsdirectory(),with a process environment as given by itsenvironment().

      Each process builder's command is checked to be a valid operatingsystem command. Which commands are valid is system-dependent,but at the very least the command must be a non-empty list ofnon-null strings.

      A minimal set of system dependent environment variables maybe required to start a process on some operating systems.As a result, the subprocess may inherit additional environment variablesettings beyond those in the process builder'senvironment().The minimal set of system dependent environment variablesmay override the values provided in the environment.

      Starting an operating system process is highly system-dependent.Among the many things that can go wrong are:

      • The operating system program file was not found.
      • Access to the program file was denied.
      • The working directory does not exist.
      • Invalid character in command argument, such as NUL.

      In such cases an exception will be thrown. The exact natureof the exception is system-dependent, but it will always be asubclass ofIOException.

      If the operating system does not support the creation ofprocesses, anUnsupportedOperationException will be thrown.

      Subsequent modifications to any of the specified builderswill not affect the returnedProcess.

      API Note:
      For example to count the unique imports for all the files in a file hierarchyon a Unix compatible platform:
          String directory = "/home/duke/src";    ProcessBuilder[] builders = {             new ProcessBuilder("find", directory, "-type", "f"),             new ProcessBuilder("xargs", "grep", "-h", "^import "),             new ProcessBuilder("awk", "{print $2;}"),             new ProcessBuilder("sort", "-u")};    List<Process> processes = ProcessBuilder.startPipeline( Arrays.asList(builders));    Process last = processes.get(processes.size() - 1);    try (InputStream is = last.getInputStream();        Reader isr = new InputStreamReader(is);        BufferedReader r = new BufferedReader(isr)) {        long count = r.lines().count();    }
      Implementation Note:
      In the reference implementation, logging of each process created can be enabled,seestart() for details.
      Parameters:
      builders - a List of ProcessBuilders
      Returns:
      aList<Process>es started from the corresponding ProcessBuilder
      Throws:
      IllegalArgumentException - any of the redirects except the standard input of the first builder and the standard output of the last builder are notProcessBuilder.Redirect.PIPE.
      NullPointerException - if an element of the command list is null or if an element of the ProcessBuilder list is null or the builders argument is null
      IndexOutOfBoundsException - if the command is an empty list (has size0)
      UnsupportedOperationException - If the operating system does not support the creation of processes
      IOException - if an I/O error occurs
      Since:
      9