OS Processes using Java ProcessBuilder

This tutorial serves as ProcessBuilder feature introduction. For some need, I was attempting to print OS environment variables using java. Generally we get that done using the versatile System class like System.getenv(); This is very old as you can see the method name itself is not as per java convention, available from JDK 1.0

Since JDK 1.5 we have got a class java.lang.ProcessBuilder which is used to create OS processes. This API is available from JDK 1.5 but key features like redirect are added in JDK 1.7. We can use this ProcessBuilder to get current thread’s environment variables as below
package com.javapapers.corejava;
 
import java.util.Map;
 
public class ProcessBuilderSample {
 
  public static void main(String args[]) {
    ProcessBuilder testProcess = new ProcessBuilder();
    Map environmentMap = testProcess.environment();
    System.out.println(environmentMap);
 
    // usual way
    System.out.println(System.getenv());
 
  }
 
}
This is not the sole purpose of this class. It helps to create and execute OS processes and also gives us lot of flexibility over the already available System class.Following example demonstrates how we can execute a set of native OS commands and get output/error redirected to a file. We can pass the commands from a file as we have done in this sample or we can pass it at run-time.
package com.javapapers.corejava;
 
import java.io.File;
import java.io.IOException;
 
public class ProcessBuilderSample {
 
  public static void main(String args[]) throws IOException {
 
    ProcessBuilder dirProcess = new ProcessBuilder("cmd");
    File commands = new File("C:/process/commands.bat");
    File dirOut = new File("C:/process/out.txt");
    File dirErr = new File("C:/process/err.txt");
 
    dirProcess.redirectInput(commands);
    dirProcess.redirectOutput(dirOut);
    dirProcess.redirectError(dirErr);
 
    dirProcess.start();
 
  }
}
To run the above program,
create a folder name “process” in C:/ and create the three files.
In commands.bat, put the following commands or something you like,
chdir
dir
date /t
echo Hello World
remember to run on JDK 1.7 and you can see the output in out.txt

0 comments:

Post a Comment