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

在Java中,通常使用System.in.read()或类似的API读取用户输入,但这些方法会等待用户按下回车键。要实现不需回车即可读取单个字符,你需要将控制台设置为“原始”模式,这在不同的操作系统上可能有不同的实现方式。讨论中提到了使用JNI或jCurses库来解决这个问题,但这些方法并不完全跨平台。
摘要由CSDN通过智能技术生成

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

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

解决方案

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.

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.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值