Reset Buffer with Bufferedreader in Java

Reset buffer with BufferedReader in Java?

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

how to clear a buffer after use?

There is not really any reason to "clear" the String "buffer". If you are worried about memory use, the String will automatically be garbage collected by the JVM when it is no longer used.

However,

str = null;

will effectively remove the reference to the String. Strings are immutable, so you can't modify the "buffer" and clear it, the best you can do is remove the reference to it and then have it garbage collected.

EDIT

To answer the question about BufferedReaders...

There is no need and no way to "clear" a BufferedReader. If you encounter an error, you can simply call readLine() again, and nothing you read before should have any effect. If you were reading from file and got an exception, you should check if you are at the end of the file, but because you are reading from keyboard, I would advise simply calling readLine() again.



Related Topics



Leave a reply



Submit