The best way to monitor output of process along with its execution
I have started a process in my Java code, this process take a very long time to run and could generate some 开发者_开发技巧output from time to time. I need to react to every output when they are generated, what is the best way to do this?
What kind of reaction are you talking about? Is the process writing to its standard output and/or standard error? If so, I suspect Process.getInputStream
and Process.getErrorStream
are what you're looking for. Read from both of those and react accordingly. Note that you may want to read from both of them from different threads, to avoid the individual buffer for either stream from filling up.
Alternatively, if you don't need the two separately, just leave redirectErrorStream
in ProcessBuilder
as false, so the error and output streams are merged.
You should start a thread which reads from the Process.getInputStream()
and getErrorStream()
(or alternatively use ProcessBuilder.redirectErrorStream(true)
) and handle it when something shows up in the stream. There are many ways that how to handle it - the right way depends on how the data is being used. Please tell more details.
Here is one real-life example: SbtRunner uses ProcessRunner to send commands to a command line application and wait for the command to finish execution (the application will print "> " when a command finishes execution). There is some indirection happening to make it easier to read from the process' output (the output is written to a MulticastPipe from where it is then read by an OutputReader).
精彩评论