![](/img/trans.png)
[英]Given n files with their lengths, divide total bytes equally among d threads equally such that any two threads differ by atmost 1 byte
[英]Counted bytes and total bytes differ
我正在编写一个Android应用程序,它将文件从资产复制到设备驱动器上的一个文件(没有权限问题,字节从资产获取到驱动器)。 我需要复制的文件大于1 MB,因此我将其拆分为多个文件,并使用类似以下内容进行复制:
try {
out = new FileOutputStream(destination);
for (InputStream file : files /* InputStreams from assets */) {
copyFile(file);
file.close();
}
out.close();
System.out.println(bytesCopied); // shows 8716288
System.out.println(new File(destination).length()); // shows 8749056
} catch (IOException e) {
Log.e("ERROR", "Cannot copy file.");
return;
}
然后,使用copyFile()
方法:
private void copyFile(InputStream file) throws IOException {
byte[] buffer = new byte[16384];
int length;
while ((length = file.read(buffer)) > 0) {
out.write(buffer);
bytesCopied += length;
out.flush();
}
}
目标文件应包含的总正确字节数是8716288(这是我查看原始文件时得到的,如果我计算Android应用程序中的写入字节数),但是new File(destination).length()
显示8749056。
我究竟做错了什么?
文件大小变得太大,因为您没有为每次写入写入length
字节,实际上每次都在写入整个缓冲区,缓冲区的length
为buffer.length()个字节。
您应该改用write(byte[] b, int off, int len)
重载,以指定每次迭代要在缓冲区中写入多少字节。
你不是要写
out.write(buffer, 0, length);
代替
out.write(buffer);
否则,即使读取的字节更少,也将始终写入完整的缓冲区。 然后,这可能会导致文件变大(原始数据之间充满了一些垃圾)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.