I've searched high and low, but can't find a definitive, up-to-date answer to my question about NIO.
Is there any way to convert from an InputStream
to a Channel
that I can use with a Selector
? It seems like Channels.newChannel()
is the only way to do the conversion but doesn't provide an instance of AbstractSelectableChannel
, which is really what I need.
More specifically, I would like to read from the stdout
and stderr
streams of a subprocess without creating one thread per stream, and it seems this is the only way to do it in pure Java. Since these streams are using pipes to pass I/O back and forth I'm surprised .newChannel
doesn't return a Pipe.SourceChannel
, which is a subclass of AbstractSelectableChannel
.
I'm using Java 7 (although if new functionality is available in 8 I would still be happy for an answer).
EDIT: I also tried casting the results of .newChannel()
to a selectable channel to no avail - it is not a selectable channel.
There is no way to do what you're asking, but you don't need a thread per stream. Just merge the streams with the API provided for the purpose, and read the output in the current thread.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With