Java ProcessBuilder Example

By Arvind Rai, 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(); 
In the example, we have created a batch file in window operating system. The batch file is test.bat given as
test.bat
echo %1%
echo %2% 
This batch command will accept two input argument. Using ProcessBuilder, we will run this batch file.
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");
	}
} 
In the example, first we have created the object of ProcessBuilder which accepts absolute path of batch file, and other arguments. Now set the working directory. Provide the location for logging. waitFor will make wait the thread until the process finished. To check command output, go to log.txt.
POSTED BY
ARVIND RAI
ARVIND RAI
LEARN MORE








©2024 concretepage.com | Privacy Policy | Contact Us