在阅读之前清除/清除System.in(stdin) [英] Flush/Clear System.in (stdin) before reading

查看:151
本文介绍了在阅读之前清除/清除System.in(stdin)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在工作中,我们有5台RFID阅读器连接到运行Linux的PC上。读者都被认为是键盘,并将他们的输入(他们从芯片中读取的内容)作为键输入事件序列发送。为了能够告诉哪个读者发送了什么序列,我正在对 / dev / input / XX 进行原始读取并以这种方式获取他们的输入。

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.

这个问题是,RFID阅读器生成的发送键盘事件仍然是instdin,当我尝试从 System.in读取时通过扫描仪(这次输入应该由普通键盘生成),我首先从读者那里获得待定输入(包括10个十六进制数字和换行符( \ n ))。

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)).

现在,问题是:如何从stdin 中清除所有这些待处理输入,然后从键盘上读取我真正想要的内容?

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?

我试过:

System.in.skip(System.in.available());

但stdin上不允许搜索( skip 抛出 IOException )。

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

for (int i = 0; i < System.in.available(); i++){
  System.in.read();
}

可用()估计不够(之后仍然在stdin中)。

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

Scanner scanner = new Scanner(System.in);
while (scanner.hasNextLine()){
  scanner.nextLine();
}
System.out.println("Clean!");

但是 hasNextLine()永远不会变成 false (打印从不执行)。

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

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String line;
while ((line = in.readLine()) != null);
System.out.println("Clean!");

与上述相同。

任何人还有更多想法吗?

Anyone with any more ideas?

推荐答案

根据 @Joni 的建议,我把它放在一起:

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

Scanner scanner = new Scanner(System.in);
int choice = 0;
while (scanner.hasNext()){
    if (scanner.hasNextInt()){
        choice = scanner.nextInt();
        break;
    } else {
        scanner.next(); // Just discard this, not interested...
    }
}

这将丢弃stdin中已挂起的数据,并等待直到输入有效数据。在此上下文中,有效,表示十进制整数。

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.

这篇关于在阅读之前清除/清除System.in(stdin)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆