我的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的代码,它也不起作用。
发布于 2010-09-22 05:18:51
我想你误解了mark是做什么的。
mark的目的是让流记住它的当前位置,这样您以后就可以使用reset()返回到它。参数不是下一步将读取多少字节--而是在标记被认为无效之前您能够读取的字节数(例如:您将不能reset()回到它;您将得到一个异常,或者在流的开始处结束)。
详情请参见the docs on InputStream。读者的mark方法的工作方式非常相似。
发布于 2010-09-22 05:12:09
这不是mark()所做的。您需要重新阅读文档。Mark允许您在流中向后移动。
https://stackoverflow.com/questions/3764479
复制相似问题