BufferedInputStream 未标记
我的 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
的代码,但它也不起作用。
A BufferedInputStream that I have isn't marking correctly. This is my code:
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));
}
}
This is outputting:
11
HelloWorld!
I want it to output
3
Hel
8
loWorld!
I also tried the code with just a pure ByteArrayInputStream as bin
, and it didn't work either.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您误解了
mark
的作用。mark
的目的是让流记住其当前位置,以便您稍后可以使用reset()
返回到该位置。参数不是接下来要读取多少字节 - 而是在标记被视为无效之前您可以读取多少字节(即:您将无法reset() 回到它;你要么得到一个异常,要么最终到达流的开头)。
有关详细信息,请参阅 InputStream 上的文档。读者的
mark
方法的工作原理非常相似。I think you're misunderstanding what
mark
does.The purpose of
mark
is to cause the stream to remember its current position, so you can return to it later usingreset()
. The argument isn't how many bytes will be read next -- it's how many bytes you'll be able to read afterward before the mark is considered invalid (ie: you won't be able toreset()
back to it; you'll either get an exception or end up at the start of the stream instead).See the docs on InputStream for details. Readers'
mark
methods work quite similarly.这不是 mark() 所做的。您需要重新阅读文档。马克让您向后穿过溪流。
That's not what mark() does. You need to re-read the documentation. Mark lets you go backward through the stream.