我是Java流的新手,我想读取特定文件的内容,然后需要从头开始阅读。我创建了一个BufferedInputStream,我对BufferedInputStream.mark(int markLimit)的文档感到困惑
文档说:
public void mark(int readlimit)
此方法通过调用reset()方法标记输入中可将流“重置”到的位置。参数readlimit是设置标记后,在标记变为无效之前可以从流中读取的字节数。例如,如果调用mark()的读取限制为10,则在调用reset()方法之前从流中读取11个字节的数据时,该标记无效,并且不需要流对象实例记住商标。
请注意,此方法可以记住的字节数可以大于内部读取缓冲区的大小。它也不依赖于支持标记/重置功能的下级流。
覆写:
类FilterInputStream中的标记
参数:
readlimit-标记无效之前可以读取的字节数**
我的代码是:
public class Test {
public static void main(String[] args) throws IOException {
File resource = new File("beforeFix.txt");
FileInputStream fileInputStream = new FileInputStream(resource);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
int i = bufferedInputStream.read();
bufferedInputStream.mark(1);
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
bufferedInputStream.reset();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
i = bufferedInputStream.read();
bufferedInputStream.reset();
}
}
在上面的代码中,我将marklimit设置为1,但是根据文档,该标记不会变为无效。
谁能用一个小例子清楚地说明我设置此设置的实际目的是什么?
提前致谢
解决方案如下:
为了使重置生效并返回到标记的位置,标记后读取的数据需要在内存中进行缓冲。标记时指定的值是应为此保留的内存量。
因此,如果您打算在调用reset之前读取100个字节,那么您的缓冲区必须至少为100个字节,这就是您必须调用mark的地方。
bufferedInputStream.mark(200);
... read no more than 200 bytes ...
bufferedInputStream.reset(); // reset back to marked position
更新
看来
mark
的文档与实际行为不匹配。该文档指出:
the maximum limit of bytes that can be read before the mark position becomes invalid
但是,看起来应该是
the minimum limit
,或者至少在不超过读取限制的前提下,如果底层实现仍然可以支持将其重置为标记的位置,则不需要丢弃这些标记。