2011-06-26 23 views
1

我正在編寫一個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.

什麼是我做錯了?

回答

6

文件大小變得太大,因爲您沒有爲每次寫入寫入length字節,您實際上每次都會寫入整個緩衝區,即buffer.length()字節長。

您應該使用write(byte[] b, int off, int len)重載來指定要在每次迭代中寫入的緩衝區中的字節數。

3

沒你的意思寫的

out.write(buffer, 0, length); 

代替

out.write(buffer); 

否則,你將永遠寫完整的緩衝,即使是讀少字節。這可能會導致更大的文件(在原始數據之間填充一些垃圾)。