Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reset buffer with BufferedReader in Java?

I am using class BufferedReader to read line by line in the buffer. When reading the last line in the buffer, I want to start reading from the beginning of the buffer again. I have read about the mark() and reset(), I am not sure its usage but I don't think they can help me out of this.

Does anyone know how to start reading from the beginning of the buffer after reaching the last line? Like we can use seek(0) of the RandomAccessFile?

like image 277
ipkiss Avatar asked Mar 24 '11 15:03

ipkiss


People also ask

What is the default buffer size for BufferedReader in java?

As per this java documentation, default buffer size is 8192 characters capacity. Line size is considered as 80 chars capacity. 8192 buffer size is sufficient for smaller file sizes.

What is a BufferedReader in java used for?

Class BufferedReader. Reads text from a character-input stream, buffering characters so as to provide for the efficient reading of characters, arrays, and lines. The buffer size may be specified, or the default size may be used. The default is large enough for most purposes.

What is InputStreamReader and BufferedReader in java?

BufferedReader reads a couple of characters from the Input Stream and stores them in a buffer. InputStreamReader reads only one character from the input stream and the remaining characters still remain in the streams hence There is no buffer in this case.

Does BufferedReader throw exception?

Sometimes BufferedReader takes data from a network stream where the reading system can fail at any time. So this type of error can occur in input operation when a BufferedReader is used. This is why a buffered reader throws IOException.


2 Answers

mark/reset is what you want, however you can't really use it on the BufferedReader, because it can only reset back a certain number of bytes (the buffer size). if your file is bigger than that, it won't work. there's no "simple" way to do this (unfortunately), but it's not too hard to handle, you just need a handle to the original FileInputStream.

FileInputStream fIn = ...;
BufferedReader bRead = new BufferedReader(new InputStreamReader(fIn));

// ... read through bRead ...

// "reset" to beginning of file (discard old buffered reader)
fIn.getChannel().position(0);
bRead = new BufferedReader(new InputStreamReader(fIn));

(note, using default character sets is not recommended, just using a simplified example).

like image 114
jtahlborn Avatar answered Oct 05 '22 06:10

jtahlborn


Yes, mark and reset are the methods you will want to use.

// set the mark at the beginning of the buffer
bufferedReader.mark(0);

// read through the buffer here...

// reset to the last mark; in this case, it's the beginning of the buffer
bufferedReader.reset();
like image 25
Greg Avatar answered Oct 05 '22 08:10

Greg