Skip to content

Instantly share code, notes, and snippets.

@ariel-co
Created March 16, 2024 16:21
Show Gist options
  • Select an option

  • Save ariel-co/0c98e0feb90f8470eb33d8ef7e023719 to your computer and use it in GitHub Desktop.

Select an option

Save ariel-co/0c98e0feb90f8470eb33d8ef7e023719 to your computer and use it in GitHub Desktop.
read process output: three ways
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.StringWriter;
public class PbReadStdout {
public static void main(String[] argv) {
try {
String[] cmd = {
// "/bin/sh", "-c",
// String.format(
// "dd if=/dev/urandom bs=%s count=1 status=none | tr -c '[:print:]\\t\\r\\n' '[.*]'",
// "64K" // 64KiB is the limit
// )
"ls", "-ld", "PbReadStdout.java", "nosuchthing", ".", "nonexistent"
};
ProcessBuilder pb = new ProcessBuilder(cmd);
// pb.redirectErrorStream(true); // merge stderr ioto stdout
// connect child process to our stdio
// pb.inheritIO();
Process process = pb.start();
StringBuilder stdout_sb = new StringBuilder();
Thread stdoutThread = new Thread(() -> {
System.out.println("starting stdoutThread");
// read all stdout+stderr afterwards
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
try {
while ((line = reader.readLine()) != null) {
System.err.println("OUT: " + line);
stdout_sb.append(line);
stdout_sb.append(System.getProperty("line.separator"
));
}
}
catch (Exception e) {
System.err.println(e);
}
});
stdoutThread.start();
StringBuilder stderr_sb = new StringBuilder();
Thread stderrThread = new Thread(() -> {
System.out.println("starting stderrThread");
// read all stdout+stderr afterwards
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getErrorStream()));
String line = null;
try {
while ((line = reader.readLine()) != null) {
System.err.println("ERR: " + line);
stderr_sb.append(line);
stderr_sb.append(System.getProperty("line.separator"));
}
}
catch (Exception e) {
System.err.println(e);
}
});
stderrThread.start();
int exitCode = process.waitFor();
System.out.printf("rc=%d\n", exitCode);
// read all unread stdout+stderr
StringBuilder sb = new StringBuilder();
BufferedReader reader =
new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
System.out.printf("Read %d bytes from input stream\n", sb.length());
// System.out.println(sb);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment