Close

Java ProcessBuilder Example

[Last Updated: Feb 11, 2016]

Java 

Java ProcessBuilder is used to create operating system processes.

Minimum JDK version required: 1.7

package com.logicbig.example;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

public class ProcessBuilderExample {

public static final List<String> getCommandOutput(String workingDirectory,
String... command)
throws IOException,
InterruptedException {

ProcessBuilder builder = new ProcessBuilder(command);

if (workingDirectory != null) {
builder.directory(new File(workingDirectory));
}

Process process = builder.start();

List<String> lines = new ArrayList<>();

try (BufferedReader br = new BufferedReader(
new InputStreamReader(
process.getInputStream()))) {

String line;
while ((line = br.readLine()) != null) {
lines.add(line);
}

process.waitFor();
}

return lines;
}


public static void main(String[] args)
throws IOException, InterruptedException {

getCommandOutput(null, "cmd.exe", "/c", "tasklist")
.forEach(System.out::println);
}
}


Note: If you want to use command like javac -help, capture Process#getErrorStream instead. It's good to capture both input and error streams together.

See Also