mankee mankee - 4 years ago 107
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(;

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

String line = stdin.nextLine();

if (!(line.contains("#"))) {

if (line.contentEquals("q")) {


Now this is easy to terminate if I simply type
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 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