Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
315 views
in Technique[技术] by (71.8m points)

java - Read Input until control+d

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...