读输入直到控制+ d [英] Read Input until control+d

查看:114
本文介绍了读输入直到控制+ d的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想提示用户开始输入字符,我希望他们能够输入字符,只要他们想要,直到他们点击控制+ d退出。



<例如,他们可以键入一串数字,如:
1234567
,一旦他们决定点击控制+ d,他们输入的行就会显示出来(所以不必点击返回)



我在想我需要一个缓冲的阅读器或其他东西。有什么建议吗?

解决方案

rlibby说的是现货:CTL-D会导致终端刷新缓冲输入到JVM 。然而,按键事件本身被终端捕获并作用,而不是通过。



幸运的是,它很容易被发现。如果用户在自己的一行上击中CTL-D,则没有要刷新的输入... JVM与EOF无法区分。因此, System.in.read()将根据 InputStream的合约返回 -1 。如果您使用 BufferedReader 包装 System.in readLine()将返回 null



这是我刚刚写的交互式命令行工具的主循环:

  BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in,UTF-8)); 

字符串行;
while((line = systemIn.readLine())!= null){
//我的程序循环。
}

有一点需要注意的是,如果用户在输入后点击CTL-D字符(但在返回之前),你会得到那些字符。我不相信有一种方法可以检测CTL-D,当它不在自己的线上时。



免责声明:我没有想法如何适用于Windows。


I want to prompt the user to begin entering characters and I want them to be able to enter characters as long as they want until they hit control+d to exit.

For example, they can type a string of numbers like: 1234567 and as soon as they decide to hit control+d the line that they entered will be displayed (so without having to hit return)

I am thinking I'll need a buffered reader or something. Any suggestions?

解决方案

What rlibby said is spot on: the CTL-D will cause the terminal to flush buffered input to the JVM. However, the keypress event itself is captured and acted on by the terminal and not passed through.

Fortunately, though, it's easy to detect. If the user hits CTL-D on a line of its own, there is no input to flush...which to the JVM is indistinguishable from EOF. Accordingly, System.in.read() will return -1 per the contract of InputStream. If you've wrapped System.in with a BufferedReader, readLine() will return null.

This is my main loop for an interactive command line tool I just wrote:

BufferedReader systemIn = new BufferedReader(new InputStreamReader(System.in, "UTF-8"));

String line;
while((line = systemIn.readLine()) != null) {
    // my program loop.
}

One thing worth pointing out is that if the user hits CTL-D after inputting characters (but before hitting return), you'll get those characters. I don't believe there's a way to detect CTL-D when it's not on a line of its own.

DISCLAIMER: I have no idea how this applies to Windows.

这篇关于读输入直到控制+ d的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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