Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to clear BufferedReader in java

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

like image 452
Surjya Narayana Padhi Avatar asked Dec 02 '09 03:12

Surjya Narayana Padhi


2 Answers

Just for readability - this is the code you posted in the comment (with the additional definition of 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.

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.

like image 165
Andreas Dolk Avatar answered Oct 22 '22 13:10

Andreas Dolk


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

like image 34
robko Avatar answered Oct 22 '22 14:10

robko