Reset buffer with BufferedReader in Java?
I am using clas开发者_如何转开发s 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
?
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();
This worked for me to resolve this problem. I'm reading in a file line by line. I'm doing a BufferedReader very early in my program. I then check if the readLine is null and perform a myFile.close and then a new BufferedReader. The first pass through, the readLine variable will be null since I set it that way globally and then haven't done a readLine yet. The variable is defined globally and set to null. As a result, a close and new BufferedReader happens. If I don't do a BufferedReader at the very beginning of my program, then this myFile.close throws an NPE on the first pass.
While the file is reading through line by line, this test fails since the readLine is not null, nothing happens in the test and the rest of the file parsing continues.
Later, when the readLine gets to EOF it is valued as null again. IE: The second pass through this check also does a myFile.close and new BufferedREader which resets the readLine back to the beginning again.
Effectively, inside my loop or outside my loop, this action only happens at the readLine variable being globally set to null or at EOF. In either case I do a "reset" to get back to the beginning of the file and a new BufferedReader.
if (readLineOutput == null) {
//end of file reached or the variable was just set up as null
readMyFile.close();
readMyFile = new BufferedReader(new FileReader("MyFile.txt"));
}
精彩评论