Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I handle multiple streams in Java?
    text
    copied!<p>I'm trying to run a process and do stuff with its input, output and error streams. The obvious way to do this is to use something like <code>select()</code>, but the only thing I can find in Java that does that is <code>Selector.select()</code>, which takes a <code>Channel</code>. It doesn't appear to be possible to get a <code>Channel</code> from an <code>InputStream</code> or <code>OutputStream</code> (<code>FileStream</code> has a <code>getChannel()</code> method but that doesn't help here)</p> <p>So, instead I wrote some code to poll all the streams:</p> <pre><code>while( !out_eof || !err_eof ) { while( out_str.available() ) { if( (bytes = out_str.read(buf)) != -1 ) { // Do something with output stream } else out_eof = true; } while( err_str.available() ) { if( (bytes = err_str.read(buf)) != -1 ) { // Do something with error stream } else err_eof = true; } sleep(100); } </code></pre> <p>which works, except that it never terminates. When one of the streams reaches end of file, <code>available()</code> returns zero so <code>read()</code> isn't called and we never get the -1 return that would indicate EOF.</p> <p>One solution would be a non-blocking way to detect EOF. I can't see one in the docs anywhere. Alternatively is there a better way of doing what I want to do?</p> <p>I see this question here: <a href="https://stackoverflow.com/questions/60302/starting-a-process-with-inherited-stdinstdoutstderr-in-java-6#60578" title="Processes with inherited stdin/stdout/stderr in Java">link text</a> and although it doesn't exactly do what I want, I can probably use that idea, of spawning separate threads for each stream, for the particular problem I have now. But surely that isn't the only way to do it? Surely there must be a way to read from multiple streams without using a thread for each?</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload