如何异步读取stdin? [英] How to asynchronously read stdin?

查看:206
本文介绍了如何异步读取stdin?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一个优雅的方式来触发一个事件,当有人可以从 System.in ?我想避免轮询 InputStream.available()

Is there an elegant way to fire an event when characters are available from System.in? I'd like to avoid polling InputStream.available().

推荐答案

你必须创建一个单独的线程,阻止读取,直到有可用的东西。

You would have to create a separate thread that blocks in read until something is available.

如果你不想真正吃掉输入,你将不得不包装一个内部缓冲区,读入缓冲区,喊叫,当被要求输入时,从缓冲区发回数据。

If you don't want to actually eat up the input, you would have to wrap it with an internal buffer, read into the buffer, shout, and when asked for the input, give back data from the buffer.

你可以这样解决:

InputStream stdin = System.in;

// Create a wrapper (with it's own dedicated read-thread)
MyListenableInputStream listenableInputStream =
        new MyListenableInputStream(stdin);

// Update System.in with something more useful.
System.setIn(listenableInputStream);

这篇关于如何异步读取stdin?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆