views:

429

answers:

3

I want to read from an java.io.InputStream with a timeout. Apparently the correct way to do this is to use java.nio.channels.SelectableChannel and java.nio.channels.Selector. Unfortunately, it's not clear how to go from an InputStream to a SelectableChannel.

The InputStream is coming from a non-conventional source -- http://java.sun.com/products/javacomm/reference/api/javax/comm/CommPort.html#getInputStream()

+1  A: 

Not all InputStreams are guaranteed to be selectable, so there is no straightforward way to do this. It's unfortunate that the CommPort class doesn't have a method for returning a SelectableChannel; there is no easy, portable way to accomplish this (i.e., without completely breaking encapsulation).

Chris Jester-Young
A: 

The question "Is it possible to read from a Java InputStream with a timeout?" is related to this one.

A: 

NIO is broken in this regard. All you have to do is look around a bit at the code and see all the casts that demand channels be SocketChannel etc. It's not possible to reuse anything in NIO for another type of filedescriptor based I/O channel like it should be.

Last I asked there were no plans to fix this for generic reuse.

Gregg Wonderly