问题描述
我正在使用 BufferedReader
类来逐行读取缓冲区中的内容.在读取缓冲区中的最后一行时,我想再次从缓冲区的开头开始读取.我已经阅读了关于 mark()
和 reset()
的内容,我不确定它的用法,但我认为它们不能帮助我解决这个问题.
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.
有谁知道如何在到达最后一行后从缓冲区的开头开始读取?就像我们可以使用 RandomAccessFile
的 seek(0)
一样?
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 是你想要的,但是你不能真正在 BufferedReader 上使用它,因为它只能重置一定数量的字节(缓冲区大小).如果你的文件比那个大,它就不会工作.没有简单"的方法来做到这一点(不幸的是),但它并不难处理,你只需要一个原始 FileInputStream 的句柄.
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).
这篇关于在 Java 中使用 BufferedReader 重置缓冲区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!