问题描述
当用户在 Java 中键入单个字符时,是否有一种简单的方法可以从控制台读取单个字符?是否可以?我已经尝试过这些方法,但它们都在等待用户按下 enter 键:
Is there an easy way to read a single char from the console as the user is typing it in Java? Is it possible? I've tried with these methods but they all wait for the user to press enter key:
char tmp = (char) System.in.read();
char tmp = (char) new InputStreamReader(System.in).read ();
char tmp = (char) System.console().reader().read(); // Java 6
我开始认为 System.in 在按下 enter 之前不知道用户输入.
I'm starting to think that System.in is not aware of the user input until enter is pressed.
推荐答案
您要做的是将控制台置于原始"模式(绕过行编辑并且不需要回车键)而不是熟"模式(行需要使用回车键进行编辑.)在 UNIX 系统上,stty"命令可以更改模式.
What you want to do is put the console into "raw" mode (line editing bypassed and no enter key required) as opposed to "cooked" mode (line editing with enter key required.) On UNIX systems, the 'stty' command can change modes.
现在,关于 Java...请参阅 Python 和 Java 中的非阻塞控制台输入.摘录:
Now, with respect to Java... see Non blocking console input in Python and Java. Excerpt:
如果您的程序必须基于控制台,你必须把你的终端关掉行模式转换为字符模式,以及记得在你之前恢复它程序退出.没有便携在整个运营过程中做到这一点的方法系统.
If your program must be console based, you have to switch your terminal out of line mode into character mode, and remember to restore it before your program quits. There is no portable way to do this across operating systems.
其中一个建议是使用 JNI.同样,这不是很便携.线程末尾的另一个建议,与上面的帖子一样,是看看使用 jCurses.
One of the suggestions is to use JNI. Again, that's not very portable. Another suggestion at the end of the thread, and in common with the post above, is to look at using jCurses.
这篇关于如何从 Java 中的控制台读取单个字符(当用户键入时)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)