Java ProcessBuilder Class



Introduction

The Java ProcessBuilder class is used to create operating system processes.This class is not synchronized.

Class Declaration

Following is the declaration for java.lang.ProcessBuilder class −

public final class ProcessBuilder
   extends Object

Class constructors

Sr.No. Constructor & Description
1

ProcessBuilder(List<String> command)

This constructs a process builder with the specified operating system program and arguments.

2

ProcessBuilder(String... command)

This constructs a process builder with the specified operating system program and arguments.

Class methods

Sr.No. Method & Description
1 List<String> command()

This method returns this process builder's operating system program and arguments.

2 ProcessBuilder command(List<String> command)

This method sets this process builder's operating system program and arguments.

3 ProcessBuilder command(String... command)

This method sets this process builder's operating system program and arguments.

4 File directory()

This method returns this process builder's working directory.

5 ProcessBuilder directory(File directory)

This method sets this process builder's working directory.

6 Map<String,String> environment()

This method returns a string map view of this process builder's environment.

7 boolean redirectErrorStream()

This method tells whether this process builder merges standard error and standard output.

8 ProcessBuilder redirectErrorStream(boolean redirectErrorStream)

This method sets this process builder's redirectErrorStream property.

9 Process start()

This method starts a new process using the attributes of this process builder.

Methods inherited

This class inherits methods from the following classes −

  • java.lang.Object

Getting process details from a Process Builder Example

The following example shows the usage of ProcessBuilder command() method. In this program, we've created a list of Strings and added notepad.exe to it. Using that list, we've initialized a ProcessBuilder instance. Now using command() method, we've printed the underlying operating system command name and other details.

package com.tutorialspoint;

import java.util.ArrayList;
import java.util.List;

public class ProcessBuilderDemo {

   public static void main(String[] args) {

      // create a new list of arguments for our process
      List<String> list = new ArrayList<String>();
      list.add("notepad.exe");
      
      // create the process builder
      ProcessBuilder pb = new ProcessBuilder(list);
      
      // get the command list
      System.out.println(pb.command());
   }
}

Output

Let us compile and run the above program, this will produce the following result −

[notepad.exe]
Advertisements