Java Process Builder

The ProcessBuilder class is used to create separate operating system processes. There are many scenarios, Where we need to launch separate operating system processes form java program.

Before JDK 5.0, We need to use the exec() method of the java.lang.Runtime class to start new process.JDK 5.0 has added ProcessBuilder to Start new OS process.

Note:

ProcessBuilder is not synchronized. If multiple threads access a ProcessBuilder instance concurrently, and at least one of the threads modifies one of the attributes structurally, it must be synchronized externally.

Starting a new process which uses the default working directory and the environment is easy:

1
2
3

Process p = new ProcessBuilder("myCommand", "myArg").start();

The ProcessBuilder class defines two constructors, such as:

1
2
3
4
5
ProcessBuilder(List<String> command);
//Constructs a process builder with the specified operating system program and arguments.

ProcessBuilder(String... command);
//Constructs a process builder with the specified operating system program and arguments

ProcessBuilder Examples.

1:Run External bat file/sh file.

In this example, we will try to run demo.bat file. The demo.bat file is at src/ root location.
The out put of process builder will be printed on consol.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class ProcessBuilderExample {

public static void main(String[] args) {

try {
System.out.println("ProcessBuilderExample.Start!!");
final File batchFile = new File("src\\demo.bat");
ProcessBuilder processBuilder = new ProcessBuilder(batchFile.getAbsolutePath());

Process process = processBuilder.start();

int resposneCode = process.waitFor();
if (resposneCode == 0) {
System.out.println("Process executed successfully");
InputStream inputStream = process.getInputStream();
String result = readInputStreamData(inputStream);
System.out.println(result);

}
} catch (Exception e) {
e.printStackTrace();
}

}

public static String readInputStreamData(InputStream input) throws IOException {
try (BufferedReader buffer = new BufferedReader(new InputStreamReader(input))) {
return buffer.lines()
.collect(Collectors.joining("\n"));
}
}

}


demo.bat File
1
echo "Hello World"
Share Comments