我们不应该在写入 OutputStream 时跟踪偏移量吗?
Shouldn't we keep track of the offset when we write to an OutputStream?
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);
.
事实是 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[])。
正如@Arnaud 评论的那样
The start is the start of the array, not of the stream. The data is in
fact appended to the previous one each time.
我不小心快速浏览了文档,从 "Writes len bytes from the specified byte array starting at offset off to this output stream" 中,我了解到 off
是流的偏移量。
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);
.
事实是 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[])。
正如@Arnaud 评论的那样
The start is the start of the array, not of the stream. The data is in fact appended to the previous one each time.
我不小心快速浏览了文档,从 "Writes len bytes from the specified byte array starting at offset off to this output stream" 中,我了解到 off
是流的偏移量。