我的 BufferedInputStream 没有正确标记。这是我的代码:
public static void main(String[] args) throws Exception {
byte[] b = "HelloWorld!".getBytes();
BufferedInputStream bin = new BufferedInputStream(new ByteArrayInputStream(b));
bin.mark(3);
while (true){
byte[] buf = new byte[4096];
int n = bin.read(buf);
if (n == -1) break;
System.out.println(n);
System.out.println(new String(buf, 0, n));
}
}
这是输出:
11
HelloWorld!
我要输出
3
Hel
8
loWorld!
我还尝试了将纯 ByteArrayInputStream 作为 bin
的代码,但它也没有工作。
最佳答案
我认为您误解了 mark
的作用。
mark
的目的是让流记住它的当前 位置,这样您以后可以使用reset()
返回到它.参数不是接下来要读取多少字节——而是在标记被视为无效之前您可以读取多少字节(即:您将无法 reset()
回到它;你要么得到一个异常,要么在流的开头结束。
参见 the docs on InputStream了解详情。读者的 mark
方法的工作原理非常相似。
关于java - BufferedInputStream 没有标记,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3764479/