Java ProcessBuilder Example
June 13, 2014
java.lang.ProcessBuilder has been introduced in JDK 5. ProcessBuilder manages operating system process. All the process attributes are stored in collection which is used by ProcessBuilder. ProcessBuilder manages the below attributes.
1. Command: List of commands to be handled.
2. Environment: System.getenv() returns the environment of current process. It can be changed.
3. working directory: Working directory can be changed where the user commands resides. Default is current working directory.
4. standard input/output: redirectInput and redirectOutput can change the standard input output.
To initiate process builder, we need to do as belwo.
Process p = new ProcessBuilder("myCommand", "myArg"); p.start();
test.bat
echo %1% echo %2%
ProcessBuilderDemo.java
package com.test; import java.io.File; import java.io.IOException; import java.lang.ProcessBuilder.Redirect; public class ProcessBuilderDemo { public static void main(String[] args) throws IOException, InterruptedException { ProcessBuilder processBuilder = new ProcessBuilder("D:/test.bat", "ABC", "XYZ"); processBuilder.directory(new File("D:/")); File log = new File("D:/log.txt"); processBuilder.redirectErrorStream(true); processBuilder.redirectOutput(Redirect.appendTo(log)); Process p = processBuilder.start(); p.waitFor(); System.out.println("Done"); } }