BufferedInputStream 未标记

发布于 2024-09-24 20:09:14 字数 658 浏览 0 评论 0原文

我的 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怪我鬧 2024-10-01 20:09:14

我认为您误解了 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 using reset(). 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 to reset() 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.

归途 2024-10-01 20:09:14

这不是 mark() 所做的。您需要重新阅读文档。马克让您向后穿过溪流。

That's not what mark() does. You need to re-read the documentation. Mark lets you go backward through the stream.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文