【问题标题】:Shouldn't we keep track of the offset when we write to an OutputStream?我们不应该在写入 OutputStream 时跟踪偏移量吗?
【发布时间】:2019-04-25 04:14:30
【问题描述】:

copyFile() 中的read() 方法从输入流中读取buf.length 字节,然后从开始到len 将它们写入输出流。

public static boolean copyFile(InputStream inputStream, OutputStream out) {
    byte buf[] = new byte[1024];
    int len;
    try {
        while ((len = inputStream.read(buf)) != -1) {
            out.write(buf, 0, len);

        }
        out.close();
        inputStream.close();
    } catch (IOException e) {
        return false;
    }
    return true;
}

如果我们总是从头开始写入输出流不会覆盖上一次迭代的数据

我们不需要跟踪偏移量吗?例如,如果第一次迭代写入 1024 字节,那么第二次迭代应该写入 out.write(buf,1024,len);

【问题讨论】:

  • 开始是数组的开始,而不是流的开始。数据实际上每次都附加到前一个。

标签: java io inputstream outputstream


【解决方案1】:

事实上,buf 是一个缓冲区,而不是整个数据流。

另外,您正在使用public int read(byte[] b) 方法,这意味着它与read(b, 0, b.length) 相同。所以缓冲区应该指向数据的下一个 buf.length 值。

更多信息,请查看https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html#read(byte[])

【讨论】:

  • 感谢您的回答。我的查询是关于 write() 但没关系,它在 cmets 中得到了回答。
【解决方案2】:

正如@Arnaud 评论的那样

开始是数组的开始,而不是流的开始。数据在 事实每次都附加到前一个。

我不小心快速扫描文档并从 “从指定的字节数组中从偏移量开始写入到此输出流的 len 个字节”,我知道off 是偏移量流的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-08-22
    • 2015-01-08
    • 2016-04-13
    • 1970-01-01
    • 1970-01-01
    • 2010-09-18
    • 1970-01-01
    • 2021-02-19
    相关资源
    最近更新 更多