I have a method which constructs a java.lang.Process instance and starts a process. Inside the method, I'd like to call process.getInputStream().transferTo(System.out); to observe how process is doing:
public Process doSth(List<String> command, File workdir) {
Process process = new ProcessBuilder(command).directory(workdir).start();
//redirect process's input stream to stdout to observe
process.getInputStream().transferTo(System.out);
...
return process;
}
But throughout the codebase, there are calls to process.getInputStream() to parse the process's text output, such as:
public void doSomethingWithProcessOutput() {
Process process = doSth(...); // call to the method above
InputStream stream = process.getInputStream();
String processResult = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))
.lines()
.collect(Collectors.joining(System.lineSeparator()));
//do something with the processResult string
}
Now if I want to observe the process by transferring the input stream to System.out, it consumes the stream, therefore subsequent calls to process.getInputStream() returns empty.
How can I both print the stream to System:out, but also re-read it when needed in other places? I tried to wrap the process' input stream with org.apache.commons.io.input.ObservableInputStream but it also consumes the stream.