实现说明
底层就是类 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);
}
}