Reset buffer with BufferedReader in Java?

69,122

Solution 1

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

Solution 2

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();
Share:
69,122
ipkiss
Author by

ipkiss

Updated on April 12, 2020

Comments

  • ipkiss
    ipkiss about 4 years

    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?

  • jtahlborn
    jtahlborn about 13 years
    this will only work if your buffer is big enough to hold the entire file.
  • user207421
    user207421 over 8 years
    This resets you to the beginning of the file, not the buffer. @ipkiss If this answers your question, your question is poorly expressed.
  • user207421
    user207421 over 8 years
    @jtahlborn There's nothing in the question about re-reading the entire file, only the current buffer, although from the accepted answer it appears the OP was asking the wrong question.
  • Saad
    Saad over 6 years
    It works but it is not the most efficient way to do it.
  • FiruzzZ
    FiruzzZ about 6 years
    it seems the only way when FileReader doesn't support mark
  • ncmathsadist
    ncmathsadist about 5 years
    What is boils down to is that the BufferedReaders is "consumed" and you must make a new one unless the file is small.