简体   繁体   中英

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). 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?

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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