我正在編寫一個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.
什麼是我做錯了?