Java ProcessBuilder Example

In this Java ProcessBuilder Example, We are showing how to run external programs and operating system commands with the help of ProcessBuilder.

We can use this java API if your JDK is above 1.5.

Each process builder manages these process attributes:

  • command, It is a list of string, each string should be a valid operating system command (see the below example)
  • environment, This will returns a copy of the environment of the current process, we are invoked.
  • working directory, It's current working directory of the process.
  • Input/Output, redirectinput/redirectOutput is for redirecting output to other resources (see the below example)



If you are using latest JDK, then ProcessBuilder will be a better choice than Runtime.getRuntime().exec()

Java ProcessBuilder Example

package com.test;

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

public class JavaProcessBuilderExample {
     * In this Java ProcessBuilder Example, We are showing how to run external
     * programs and operating system process
public static void main(String[] args) throws IOException {
List<String> command = new ArrayList<String>();

// For linux
// For windows
        // command.add("notepad.exe");
        // command.add("C:\\file.txt");
ProcessBuilder processbuilder = new ProcessBuilder(command);
// Redirect output to this file.
processbuilder.redirectOutput(new File("test.txt"));

final Process process = processbuilder.start();
        InputStream inputStream = process.getInputStream
        InputStreamReader inputStreamReader =
new InputStreamReader(inputStream);
        BufferedReader bufferedReader =
new BufferedReader(inputStreamReader);
        String line;
while ((line = bufferedReader.readLine()) != null) {
// waitFor() method is used to wait till the process returns the exit value
try {
int exitValue = process.waitFor();
("Exit Value is " + exitValue);
} catch (InterruptedException e) {
System.out.println("Program terminated!");
contents of test.txt
09:30:52 up  1:33,  1 user,  load average: 0.26, 0.37, 0.26


Your email address will not be published. Required fields are marked *