简体   繁体   English

计数字节和总字节不同

[英]Counted bytes and total bytes differ

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). 我正在编写一个Android应用程序,它将文件从资产复制到设备驱动器上的一个文件(没有权限问题,字节从资产获取到驱动器)。 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: 我需要复制的文件大于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;
}

Then, the copyFile() method: 然后,使用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();
    }
}

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. 目标文件应包含的总正确字节数是8716288(这是我查看原始文件时得到的,如果我计算Android应用程序中的写入字节数),但是new File(destination).length()显示8749056。

What am I doing wrong? 我究竟做错了什么?

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. 文件大小变得太大,因为您没有为每次写入写入length字节,实际上每次都在写入整个缓冲区,缓冲区的length为buffer.length()个字节。

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. 您应该改用write(byte[] b, int off, int len)重载,以指定每次迭代要在缓冲区中写入多少字节。

Didn't you mean to write 你不是要写

out.write(buffer, 0, length);

instead of 代替

out.write(buffer);

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). 然后,这可能会导致文件变大(原始数据之间充满了一些垃圾)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM