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.
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.");
}
}
}
OUTPUTError 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.