ProcessBuilder
public
final
class
ProcessBuilder
extends Object
| java.lang.Object | |
| ↳ | java.lang.ProcessBuilder |
This class is used to create operating system processes.
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.
Each process builder manages these process attributes:
- a command, a list of strings which signifies the external program file to be invoked and its arguments, if any. Which string lists represent a valid operating system command is system-dependent. For example, it is common for each conceptual argument to be an element in this list, but there are operating systems where programs are expected to tokenize command line strings themselves - on such a system a Java implementation might require commands to contain exactly two elements.
- an environment, which is a system-dependent mapping from
variables to values. The initial value is a copy of
the environment of the current process (see
getenv()). - a working directory. The default value is the current
working directory of the current process, usually the directory
named by the system property
user.dir.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 thatstart()will fail. For example, setting the command attribute to an empty list will not throw an exception unlessstart()is invoked.Note that this class is not synchronized. If multiple threads access a
ProcessBuilderinstance 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:
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")); Process p = pb.start();To start a process with an explicit set of environment variables, first call
Map.clear()before adding environment variables.Summary
Public constructors
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.
Public methods
List<String>command()Returns this process builder's operating system program and arguments.
ProcessBuildercommand(String... command)Sets this process builder's operating system program and arguments.
ProcessBuildercommand(List<String> command)Sets this process builder's operating system program and arguments.
Filedirectory()Returns this process builder's working directory.
ProcessBuilderdirectory(File directory)Sets this process builder's working directory.
Map<String, String>environment()Returns a string map view of this process builder's environment.
booleanredirectErrorStream()Tells whether this process builder merges standard error and standard output.
ProcessBuilderredirectErrorStream(boolean redirectErrorStream)Sets this process builder's
redirectErrorStreamproperty.Processstart()Starts a new process using the attributes of this process builder.
Inherited methods
From
class
java.lang.ObjectPublic constructors
ProcessBuilder
Added in API level 1ProcessBuilder (List<String> command)
Constructs a process builder with the specified operating system program and arguments. This constructor does not make a copy of the
commandlist. Subsequent updates to the list will be reflected in the state of the process builder. It is not checked whethercommandcorresponds to a valid operating system command.Parameters commandList: the list containing the program and its argumentsThrows NullPointerExceptionif the argument is null ProcessBuilder
Added in API level 1ProcessBuilder (String... command)
Constructs a process builder with the specified operating system program and arguments. This is a convenience constructor that sets the process builder's command to a string list containing the same strings as the
commandarray, in the same order. It is not checked whethercommandcorresponds to a valid operating system command.Parameters commandString: a string array containing the program and its argumentsPublic methods
command
Added in API level 1List<String> command ()
Returns this process builder's operating system program and arguments. The returned list is not a copy. Subsequent updates to the list will be reflected in the state of this process builder.
Returns List<String>this process builder's program and its arguments command
Added in API level 1ProcessBuilder command (String... command)
Sets this process builder's operating system program and arguments. This is a convenience method that sets the command to a string list containing the same strings as the
commandarray, in the same order. It is not checked whethercommandcorresponds to a valid operating system command.Parameters commandString: a string array containing the program and its argumentsReturns ProcessBuilderthis process builder command
Added in API level 1ProcessBuilder command (List<String> command)
Sets this process builder's operating system program and arguments. This method does not make a copy of the
commandlist. Subsequent updates to the list will be reflected in the state of the process builder. It is not checked whethercommandcorresponds to a valid operating system command.Parameters commandList: the list containing the program and its argumentsReturns ProcessBuilderthis process builder Throws NullPointerExceptionif the argument is null directory
Added in API level 1File directory ()
Returns this process builder's working directory. Subprocesses subsequently started by this object's
start()method will use this as their working directory. The returned value may benull-- this means to use the working directory of the current Java process, usually the directory named by the system propertyuser.dir, as the working directory of the child process.Returns Filethis process builder's working directory directory
Added in API level 1ProcessBuilder directory (File directory)
Sets this process builder's working directory. Subprocesses subsequently started by this object's
start()method will use this as their working directory. The argument may benull-- this means to use the working directory of the current Java process, usually the directory named by the system propertyuser.dir, as the working directory of the child process.Parameters directoryFile: the new working directoryReturns ProcessBuilderthis process builder environment
Added in API level 1Map<String, String> environment ()
Returns a string map view of this process builder's environment. Whenever a process builder is created, the environment is initialized to a copy of the current process environment (see
getenv()). Subprocesses subsequently started by this object'sstart()method will use this map as their environment.The returned object may be modified using ordinary
Mapoperations. These modifications will be visible to subprocesses started via thestart()method. TwoProcessBuilderinstances always contain independent process environments, so changes to the returned map will never be reflected in any otherProcessBuilderinstance or the values returned bySystem.getenv.If the system does not support environment variables, an empty map is returned.
The returned map does not permit null keys or values. Attempting to insert or query the presence of a null key or value will throw a
NullPointerException. Attempting to query the presence of a key or value which is not of typeStringwill throw aClassCastException.The behavior of the returned map is system-dependent. A system may not allow modifications to environment variables or may forbid certain variable names or values. For this reason, attempts to modify the map may fail with
UnsupportedOperationExceptionorIllegalArgumentExceptionif the modification is not permitted by the operating system.Since the external format of environment variable names and values is system-dependent, there may not be a one-to-one mapping between them and Java's Unicode strings. Nevertheless, the map is implemented in such a way that environment variables which are not modified by Java code will have an unmodified native representation in the subprocess.
The returned map and its collection views may not obey the general contract of the
equals(Object)andhashCode()methods.The returned map is typically case-sensitive on all platforms.
If a security manager exists, its
checkPermissionmethod is called with aRuntimePermission("getenv.*")permission. This may result in aSecurityExceptionbeing thrown.When passing information to a Java subprocess, system properties are generally preferred over environment variables.
Returns Map<String, String>this process builder's environment Throws SecurityExceptionif a security manager exists and its checkPermissionmethod doesn't allow access to the process environmentredirectErrorStream
Added in API level 1boolean redirectErrorStream ()
Tells whether this process builder merges standard error and standard output.
If this property is
true, then any error output generated by subprocesses subsequently started by this object'sstart()method will be merged with the standard output, so that both can be read using thegetInputStream()method. This makes it easier to correlate error messages with the corresponding output. The initial value isfalse.Returns booleanthis process builder's redirectErrorStreampropertyredirectErrorStream
Added in API level 1ProcessBuilder redirectErrorStream (boolean redirectErrorStream)
Sets this process builder's
redirectErrorStreamproperty.If this property is
true, then any error output generated by subprocesses subsequently started by this object'sstart()method will be merged with the standard output, so that both can be read using thegetInputStream()method. This makes it easier to correlate error messages with the corresponding output. The initial value isfalse.Parameters redirectErrorStreamboolean: the new property valueReturns ProcessBuilderthis process builder start
Added in API level 1Process start ()
Starts a new process using the attributes of this process builder.
The new process will invoke the command and arguments given by
command(), in a working directory as given bydirectory(), with a process environment as given byenvironment().This method checks that the command is a valid operating system command. Which commands are valid is system-dependent, but at the very least the command must be a non-empty list of non-null strings.
A minimal set of system dependent environment variables may be required to start a process on some operating systems. As a result, the subprocess may inherit additional environment variable settings beyond those in the process builder's
environment().If there is a security manager, its
checkExecmethod is called with the first component of this object'scommandarray as its argument. This may result in aSecurityExceptionbeing thrown.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.
In such cases an exception will be thrown. The exact nature of the exception is system-dependent, but it will always be a subclass of
IOException.Subsequent modifications to this process builder will not affect the returned
Process.Returns Processa new Processobject for managing the subprocessThrows NullPointerExceptionif an element of the command list is null IndexOutOfBoundsExceptionif the command is an empty list (has size 0)SecurityExceptionif a security manager exists and - its
checkExecmethod doesn't allow creation of the subprocess, or
IOExceptionif an I/O error occurs See also:
Annotations
Interfaces
Classes
- Boolean
- Byte
- Character
- Character.Subset
- Character.UnicodeBlock
- Class
- ClassLoader
- Compiler
- Double
- Enum
- Float
- InheritableThreadLocal
- Integer
- Long
- Math
- Number
- Object
- Package
- Process
- ProcessBuilder
- Runtime
- RuntimePermission
- SecurityManager
- Short
- StackTraceElement
- StrictMath
- String
- StringBuffer
- StringBuilder
- System
- Thread
- ThreadGroup
- ThreadLocal
- Throwable
- Void
Enums
Exceptions
- ArithmeticException
- ArrayIndexOutOfBoundsException
- ArrayStoreException
- ClassCastException
- ClassNotFoundException
- CloneNotSupportedException
- EnumConstantNotPresentException
- Exception
- IllegalAccessException
- IllegalArgumentException
- IllegalMonitorStateException
- IllegalStateException
- IllegalThreadStateException
- IndexOutOfBoundsException
- InstantiationException
- InterruptedException
- NegativeArraySizeException
- NoSuchFieldException
- NoSuchMethodException
- NullPointerException
- NumberFormatException
- ReflectiveOperationException
- RuntimeException
- SecurityException
- StringIndexOutOfBoundsException
- TypeNotPresentException
- UnsupportedOperationException
Errors
- AbstractMethodError
- AssertionError
- ClassCircularityError
- ClassFormatError
- Error
- ExceptionInInitializerError
- IllegalAccessError
- IncompatibleClassChangeError
- InstantiationError
- InternalError
- LinkageError
- NoClassDefFoundError
- NoSuchFieldError
- NoSuchMethodError
- OutOfMemoryError
- StackOverflowError
- ThreadDeath
- UnknownError
- UnsatisfiedLinkError
- UnsupportedClassVersionError
- VerifyError
- VirtualMachineError

