Java: use NIO with System.in [duplicate]

2020-07-11 04:14发布

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?

3条回答
ゆ 、 Hurt°
2楼-- · 2020-07-11 04:43

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);
查看更多
甜甜的少女心
3楼-- · 2020-07-11 05:02

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)

查看更多
男人必须洒脱
4楼-- · 2020-07-11 05:02

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.

查看更多
登录 后发表回答