mankee mankee - 1 year ago 61
Java Question

How can I test with stdin if Ctrl + d has been pressed?

I'm reading from standard input using the following loop:

Scanner stdin = new Scanner(System.in);

while (stdin.hasNextLine() && stdin.nextLine() != null) {

String line = stdin.nextLine();

if (!(line.contains("#"))) {
input.add(line);
}

if (line.contentEquals("q")) {
break;
}

}


Now this is easy to terminate if I simply type
q
and press enter, however I'm supposed to terminate the program when the user presses
Ctrl + d
on a new line. I can't get this to work, when I press
Ctrl + d
nothing happens.

Answer Source

The problem is that hasNextLine() and hasLine() wait for the user to input "enter".

Ctrl-D is not ... enter.

So you have to look into means that go "character by character" for example.

Maybe scanner.next() will return something more useful instead.

Beyond that, things are even more complicated, see here for example.

Thus, the real, not so helpful answer is actually: Java scanner and "ctrl-something" keystrokes are not exactly best friends.

You could probably look into some libraries providing curses like functionality instead.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download