ProcessBuilder Redirects Streams To Files

Capture subprocess stdout and stderr into separate files with Redirect.to, so logs survive waitFor and the two streams never interleave.

JavaCli Tooling

Code

snippet
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;

public class BuildProbe {

    public static void main(String[] args) throws IOException, InterruptedException {
        Path stdoutLog = Files.createTempFile("probe-out-", ".log");
        Path stderrLog = Files.createTempFile("probe-err-", ".log");

        // Redirect.to redirects both streams to separate files, 互不混流
        Process process = new ProcessBuilder("java", "--version")
                .redirectOutput(ProcessBuilder.Redirect.to(stdoutLog.toFile()))
                .redirectError(ProcessBuilder.Redirect.to(stderrLog.toFile()))
                .start();

        int exit = process.waitFor();
        System.out.println("exit code: " + exit);
        System.out.println("stdout bytes: " + Files.size(stdoutLog));
        // waitFor 之后按文件回读;exit code 与字节数都是进程真实产物
        System.out.println("stderr lines: " + Files.readAllLines(stderrLog).size());

        Files.deleteIfExists(stdoutLog);
        Files.deleteIfExists(stderrLog);
    }
}

What executes and why

Structurally, expect the class BuildProbe and nothing else.

Points of care

  • All that is required beforehand is the language toolchain.

Applying it

Look for the exit code:, stdout bytes:, stderr lines: prefixes when the file executes; they let each line point back to its step.

Statements that matter

.redirectOutput(ProcessBuilder.Redirect.to(stdoutLog.toFile()))
.redirectError(ProcessBuilder.Redirect.to(stderrLog.toFile()))
.start();
Path stdoutLog = Files.createTempFile("probe-out-", ".log");
Path stderrLog = Files.createTempFile("probe-err-", ".log");

Interactive Tools for This Topic

FAQ

What does ProcessBuilder Redirects Streams To Files print when run?
Execute the whole file; each printed line is prefixed with a label like `exit code:`, `stdout bytes:`, `stderr lines:`.