Menu
Topics Index
...
`


Exploring java.lang >
Siva Nookala - 06 Oct 2016
ProcessBuilder provides another way to start and manage process (that is, program). As explained earlier, all process are represented by the process class, and a Java Process Class can be started by Runtime.exec(). ProcessBuilder offers more control over the processes.

process builder defines these construction
ProcessBuilder(List<String> agrs)
ProcessBuilder(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.

MethodDescription
List<String>command()Returns a reference to a List that contains the name to program and its arguments. Changes to this list affect the invoking process
File directory() Returns the current working directory of the invoking object. This value will be null if the directory is the same as that of the java program that started the process
ProcessBuilder directory(File dir)Sets the current working directory of the invoking object. Returns a reference to the invoking object.
Process start()
throws IOException
Begins the process specified by the invoking. In other words, it returns the specified program
boolean redirectErrorStream()Returns true if the standard error stream has been redirected to the standard output stream. Returns flase if the streams are seperated.
ProcessBuilderDemo
class ProcessBuilderDemo
{
    public static void main(String arg[])
    {
        try
        {
            ProcessBuilder proc = new ProcessBuilder("notepad.exe", "testfile");
            proc.start();
        } catch (Exception e)
        {
            System.out.println("Error Executing notepad.");
        }    
    }
}
OUTPUT

Error Executing notepad.

DESCRIPTION

  • 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.

THINGS TO TRY
  • Basically if you execute this program in your corresponding desktops or in your laptops it will display a notepad window and with a file name testfile.
  • Otherwise an exception will rise as show in the program, here in this program first it tries to execute the try block but it failed and immediately it goes to the preceding one catch block, here catch block catches the exception and displays the exception.

0
Wrong
Score more than 2 points

© meritcampus 2016 - 2017

All Rights Reserved.