【发布时间】: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