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
?
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.
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.
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.
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.
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).
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With