如何在java中清除BufferedReader

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1830520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 23:04:00  来源:igfitidea点击:

How to clear BufferedReader in java

javaclearbufferedreader

提问by Surjya Narayana Padhi

To read data from my serial port I am using an inputStream and using BufferedReaderfor the inputStream. After each read I want to clear the BufferedReader. Under the class BufferedReaderthere is no clear method. I tried to use reset()but it didn't work. Any geeks here to suggest anything on this problem?

为了从我的串行端口读取数据,我使用了 inputStream 并BufferedReader用于 inputStream。每次阅读后,我想清除BufferedReader. 在类下BufferedReader没有明确的方法。我尝试使用,reset()但没有用。这里有任何极客就这个问题提出任何建议吗?

回答by Andreas Dolk

Just for readability - this is the code you posted in the comment (with the additional definition of str)

只是为了可读性 - 这是您在评论中发布的代码(带有 str 的附加定义)

DataInputStream inStream = null;
String str = null; 
BufferedReader bufRd = new BufferedReader(new InputStreamReader(inStream)); 
while((str = bufRd.readLine()) != null){ 
  System.out.println(str); 
}

Yes, it should work. There is no need to 'clear' or 'reset' a Stream or a Streamreader. Everything you read from the reader is 'taken from it', you will not see it again with the next read.

是的,它应该工作。无需“清除”或“重置”Stream 或Streamreader。你从读者那里读到的一切都是“取自它的”,下次阅读时你不会再看到它。

So if you really see items reappear on the Reader (and you haven't 'customized' the reader itself), then it is most likely, that your data source is sending the same data again and again. Check in that area.

因此,如果您真的看到项目重新出现在阅读器上(并且您没有“自定义”阅读器本身),那么很可能是您的数据源一次又一次地发送相同的数据。检查那个区域。

回答by robko

Try to make a new instance of buffer

尝试创建一个新的缓冲区实例

BufferedReader br = new BufferedReader(newInputStreamReader(socket.getInputStream())); //create
String read = br.readLine(); //read line
br = new BufferedReader(newInputStreamReader(socket.getInputStream()));

I'm using socket communication so here is socket example. I hope I helped you

我正在使用套接字通信,所以这里是套接字示例。我希望我能帮助你