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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…