Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

InputStream to Channel for Selector

Tags:

java

nio

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.

like image 255
Dan Avatar asked Oct 20 '22 15:10

Dan


1 Answers

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.

like image 61
user207421 Avatar answered Nov 01 '22 18:11

user207421