如何从 Java 中的控制台读取单个字符(当用户键入时)?

时间:2023-01-12
本文介绍了如何从 Java 中的控制台读取单个字符(当用户键入时)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

当用户在 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 中的控制台读取单个字符(当用户键入时)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:没有制定目标 NDK 的规则 下一篇:创建一个“命令"安慰

相关文章

最新文章