← 中文资源

简体中文版本

ProcessBuilder 流重定向到文件

用 Redirect.to 把子进程的 stdout 与 stderr 分别写进文件,waitFor 结束后按文件回读字节数,两条流永不混流,诊断日志在进程退出后依然可读。

阅读英文原文

实现说明

底层就是类 BuildProbe。

使用要点

  • 每一步打印都带着自己的标签:exit code:、stdout bytes:、stderr lines:。

常见问题

运行「ProcessBuilder 流重定向到文件」会打印什么?

运行文件本身,exit code:、stdout bytes:、stderr lines: 这些前缀各对应一段演示逻辑。

核心语句

.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");

代码示例

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);
    }
}