Reset buffer with BufferedReader in Java?

余生颓废 提交于 2019-11-26 16:39:18

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"));
                }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!