如何从Java中的控制台读取单个字符(用户键入它)? [英] How to read a single char from the console in Java (as the user types it)?

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

问题描述

是否有一种简单的方法来从控制台读取单个字符,因为用户正在用Java键入它?是否可以?我试过这些方法,但他们都等待用户按

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不知道用户输入

I'm starting to think that System.in is not aware of the user input until enter is pressed.

推荐答案

你想做的是将控制台放入raw模式(需要线路编辑,不需要输入密钥),而不是熟模式(需要输入密钥的线路编辑)。在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.

还有一个有趣的讨论线程< a href =http://forums.sun.com/thread.jspa?threadID=570709 =nofollow noreferrer>此处。其中一个建议是使用JNI。再次,这不是很方便。在会话结束时的另一个建议,与上面的帖子一样,是使用 jCurses a>。

There's also an interesting discussion thread here. 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中的控制台读取单个字符(用户键入它)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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