计数字节和总字节不同
我正在编写一个 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.
我做错了什么?
I'm writing an Android application which copies files from the assets to one file on the device's drive (no permission problems, bytes get from the assets to the drive). The file that I need to copy is larger than 1 MB, so I split it up into multiple files, and I copy them with something like:
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;
}
Then, the copyFile()
method:
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();
}
}
The correct number of total bytes that the destination file should contain is 8716288 (that's what I get when I look at the original files and if I count the written bytes in the Android application), but new File(destination).length()
shows 8749056.
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
文件大小变得太大,因为您没有为每次写入写入
length
字节,您实际上每次都写入整个缓冲区,即 buffer.length() 字节长。您应该使用
write(byte[] b, int off, int len)
重载,以指定要写入缓冲区中的字节数每个迭代。The file size becomes too large because you are not writing
length
bytes for each write, you are actually writing the whole buffer each time, which is buffer.length() bytes long.You should use the
write(byte[] b, int off, int len)
overload instead, to specify how many bytes in the buffer you want to be written on each iteration.你不是想写
而不是
否则你总是会写完整的缓冲区,即使读取的字节较少。这可能会导致文件更大(原始数据之间充满了一些垃圾)。
Didn't you mean to write
instead of
Otherwise you would always write the complete buffer, even if less bytes were read. This may then lead to a larger file (filled with some garbage between your original data).