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)

Reference-> http://docs.oracle.com/javase/7/docs/api/java/lang/ProcessBuilder.html

Note

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.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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
       
command.add("uptime");
      
       
// 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) {
           
System.out.println(line);
       
}
       
// waitFor() method is used to wait till the process returns the exit value
       
try {
           
int exitValue = process.waitFor();
            System.out.println
("Exit Value is " + exitValue);
       
} catch (InterruptedException e) {
           
e.printStackTrace();
       
}
       
System.out.println("Program terminated!");
   
}
}
Output
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 *