Skip to content

Instantly share code, notes, and snippets.

@jeff303
Last active April 4, 2019 15:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeff303/e5b44e220db20800752c932cbfbf7ed1 to your computer and use it in GitHub Desktop.
Save jeff303/e5b44e220db20800752c932cbfbf7ed1 to your computer and use it in GitHub Desktop.
Capture output of process launched by ProcessBuilder
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringJoiner;
public class ProcessBuilderRunner {
public static void main(String[] args) {
final ProcessBuilder pb = new ProcessBuilder(args);
final String output = runCommandForOutput(pb);
System.out.printf("full stdout from process: %s\n", output);
}
private static String runCommandForOutput(ProcessBuilder processBuilder) {
Process process;
String result = "";
try {
final String separator = System.getProperty("line.separator");
final StringJoiner cmdJoiner = new StringJoiner(" ");
processBuilder.command().forEach(part -> cmdJoiner.add(part));
System.out.printf("About to run: %s\n", cmdJoiner);
final StringJoiner joiner = new StringJoiner(separator);
final StringJoiner errorJoiner = new StringJoiner(separator);
process = processBuilder.start();
final Thread outputReaderThread = new Thread(() -> {
final BufferedReader outputReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
outputReader.lines().iterator().forEachRemaining(line -> {
System.out.printf("stdout line: %s\n", line);
joiner.add(line);
});
});
final Thread errorReaderThread = new Thread(() -> {
final BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
errorReader.lines().iterator().forEachRemaining(line -> {
System.err.printf("stderr line: %s\n", line);
errorJoiner.add(line);
});
});
outputReaderThread.start();
errorReaderThread.start();
final int exitValue = process.waitFor();
outputReaderThread.join();
errorReaderThread.join();
System.out.printf("exit value from process: %d\n", exitValue);
process.destroy();
result = joiner.toString();
System.err.printf("stderr from process: %s\n", errorJoiner.toString());
} catch (IOException | InterruptedException e) {
System.err.printf(
"%s caught when trying to run process and capture stdout/stderr: %s\n",
e.getClass().getSimpleName(),
e.getMessage()
);
e.printStackTrace(System.err);
}
return result;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment