Home » Java programming language

Java ProcessBuilder start() method with example

ProcessBuilder Class start() method: Here, we are going to learn about the start() method of ProcessBuilder Class with its syntax and example.
Submitted by Preeti Jain, on December 13, 2019

ProcessBuilder Class start() method

  • start() method is available in java.lang package.
  • start() method is used to kick or start a new process using the set attributes of process builder and it checks the calling command is valid operating system command and check system dependent command invalid commands.
  • start() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
  • start() method may throw an exception at the time of starting a new process.
    • SecurityException: This exception may throw when its checkExec() method is not permitted to create the child process.
    • IndexOutOfBoundsException: This exception may throw when the list of commands is blank.
    • IOException:This exception may throw during input/output errors.
    • NullPointerException: This exception may throw when null exists in the list of commands.

Syntax:

    public Process start();

Parameter(s):

  • It does not accept any parameter.

Return value:

The return type of this method is Process, it returns newly created process to operate child processes.

Example:

// Java program to demonstrate the example 
// of Process start() method of ProcessBuilder 

import java.io.*;
import java.util.*;

public class RedirectErrorStream {
    public static void main(String[] args) throws Exception {
        // Creating an object of List
        List l = new LinkedList();

        // By using add() method to add elements
        l.add("TextPad.exe");
        l.add("notepad.exe");

        // Instantiating ProcessBuilder object
        ProcessBuilder pr_bu = new ProcessBuilder(l);

        // Start a process
        Process p = pr_bu.start();

        // Every process exit with a exit value
        int val = p.waitFor();

        System.out.println("Exit value = " + val);
    }
}

Output

Exception in thread "main" java.io.IOException: CreateProcess: TextPad.exe notep
ad.exe error=2
        at java.lang.ProcessImpl.create(Native Method)
        at java.lang.ProcessImpl.(ProcessImpl.java:81)
        at java.lang.ProcessImpl.start(ProcessImpl.java:30)
        at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
        at RedirectErrorStream.main(RedirectErrorStream.java:17)


Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.