Home | | Web Programming | ProcessBuilder

Chapter: Java The Complete Reference : The Java Library : Exploring java.lang

ProcessBuilder

ProcessBuilder provides another way to start and manage processes (that is, programs).

ProcessBuilder

 

ProcessBuilder provides another way to start and manage processes (that is, programs). As explained earlier, all processes are represented by the Process class, and a process can be started by Runtime.exec( ). ProcessBuilder offers more control over the processes. For example, you can set the current working directory.

ProcessBuilder defines these constructors:

 

ProcessBuilder(List<String> args) ProccessBuilder(String ... args)

 

Here, args is a list of arguments that specify the name of the program to be executed along with any required command-line arguments. In the first constructor, the arguments are passed in a List. In the second, they are specified through a varargs parameter. Table 17-12 describes the methods defined by ProcessBuilder.

 

In Table 17-12, notice the methods that use the ProcessBuilder.Redirect class. This abstract class encapsulates an I/O source or target linked to a subprocess. Among other things, these methods enable you to redirect the source or target of I/O operations. For example, you can redirect to a file by calling to( ), redirect from a file by calling from( ), and append to a file by calling appendTo( ). A File object linked to the file can be obtained by calling file( ). These methods are shown here:

 

static ProcessBuilder.Redirect to(File f ) static ProcessBuilder.Redirect from(File f )

static ProcessBuilder.Redirect appendTo(File f ) File file( )

Another method supported by ProcessBuilder.Redirect is type( ), which returns a value of the enumeration type ProcessBuilder.Redirect.Type. This enumeration describes the type of the redirection. It defines these values: APPEND, INHERIT, PIPE, READ, or WRITE.

ProcessBuilder.Redirect also defines the constants INHERIT and PIPE.




To create a process using ProcessBuilder, simply create an instance of ProcessBuilder, specifying the name of the program and any needed arguments. To begin execution of the program, call start( ) on that instance. Here is an example that executes the Windows text editor notepad. 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.");

}

 

}

 

}

 

Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail
Java The Complete Reference : The Java Library : Exploring java.lang : ProcessBuilder |


Privacy Policy, Terms and Conditions, DMCA Policy and Compliant

Copyright © 2018-2024 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.