Skip to content
Advertisement

Flush/Clear System.in (stdin) before reading

At work, we have 5 RFID readers attached to a PC running Linux. The readers are all recognized as keyboards and send their input (what they read form the Chip) as an key-input-event sequence. To be able to tell which reader send what sequence, I’m doing a raw-read over /dev/input/XX and get their input this way.

The problem with this is, that the send keyboard-events generated by the RFID readers are still “in” stdin and when I try to read from System.in via Scanner (input should be generated by a normal keyboard this time), I first get the “pending” input from the readers (which consists of 10 Hex-decimal digits and a newline (n)).

Now, the question is: How can I flush all these “pending” input’s from stdin and then read what I really want from the keyboard?

I tried:

JavaScript

But seek is not allowed on stdin (skip throws an IOException).

JavaScript

But available() doesn’t estimate enough (still stuff in stdin afterwards).

JavaScript

But hasNextLine() never becomes false (the print never executes).

JavaScript

Same as above.

Anyone with any more ideas?

Advertisement

Answer

Based on @Joni‘s advice, i put this together:

JavaScript

This discards the data that is already “pending” in stdin and waits until valid data is entered. Valid, in this context, meaning a decimal integer.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement