6

Is it possible to use NIO with System.in?

I would like to somehow treat 'stdin' as a selectable channel. Has anyone found a way to do this?

Justin
  • 4,437
  • 6
  • 32
  • 52

3 Answers3

2

I don't know about a SelectableChannel, but you can convert an InputStream to a ReadableByteChannel with

using java.nio.channels.Channels;

...

ReadableByteChannel in = Channels.newChannel(System.in);
Powerlord
  • 87,612
  • 17
  • 125
  • 175
0

You could create a Pipe and a custom thread to read from standard input and write to the pipe.

Once you have the Pipe you can then get the input channel.

Archie
  • 4,959
  • 1
  • 30
  • 36
-1

duplicate:

How to get SelectableChannel from an InputStream?

hmmm... on second thought, for stdin there may be a solution. I found this reference:

http://www.javafaq.nu/java-example-code-346.html

and in particular:

SystemInPipe.java (class which encapsulates stdin as a selectable channel)

Community
  • 1
  • 1
Jason S
  • 184,598
  • 164
  • 608
  • 970
  • 2
    I appreciate what that guy is trying to do in SystemInPipe, but its still not much better than spawning a daemon thread to poll it. Problem is you can't interrupt that thread (ever). – Justin Apr 03 '10 at 23:57
  • 4
    This is a classic example of why answers that are primarily links are strongly discouraged on StackOverflow. The link to `javafaq.nu` is dead, so the answer is worthless. – Jim Garrison Jul 15 '16 at 17:54