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.
Code
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
Git Conventional Commit BuilderBuild and validate Conventional Commits v1.0.0 messages with type, scope, breaking markers, 72-char subject counter, body, footers, and git CLI command.Glob Pattern TesterCompile glob patterns with *, **, ?, character classes, and braces into regex and test them against a list of candidate file paths.Tar Archive Command BuilderBuild safe tar create, extract, and list commands for gzip, xz, zstd, and bzip2 archives with excludes, target directory (-C), and flag explanations.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.