2012-05-24 18 views
0

我使用BufferedInputStream複製文件。 我在循環中複製byte []。 這對於大文件來說非常緩慢。android:將一個文件複製到另一個文件的更快解決方案

我看到了FileChannel結構。我也嘗試過使用它。我想知道FileChannel是否比使用IOSTreams更好。在我的測試中,我無法看到主要的性能改進。

還有沒有其他更好的解決方案。

我的要求是修改前1000個字節的src的文件,並拷貝到目標,複製SRC文件的字節的其餘部分目標文件。

隨着fileChannel

private void copyFile(File sourceFile, File destFile,byte[] buffer,int srcOffset, int destOffset) { 
    try { 
     if (!sourceFile.exists()) { 
      return; 
     } 
     if (!destFile.exists()) { 
      destFile.createNewFile(); 
     } 
     FileChannel source = null; 
     FileChannel destination = null; 
     source = new FileInputStream(sourceFile).getChannel(); 
     source.position(srcOffset); 
     destination = new FileOutputStream(destFile).getChannel(); 
     destination.write(ByteBuffer.wrap(buffer)); 
     if (destination != null && source != null) { 
      destination.transferFrom(source, destOffset, source.size()-srcOffset); 
     } 
     if (source != null) { 
      source.close(); 
     } 
     if (destination != null) { 
      destination.close(); 
     } 

    } catch (Exception ex) { 
     ex.printStackTrace(); 
    } 
} 

使用I/O流

while ((count = random.read(bufferData)) != -1) { 

      fos.write(bufferData, 0, count); 
     } 
+2

沒有看到你的代碼,這是不可能回答這個問題。 – EJP

+0

我已經添加了代碼部分 – png

+0

你說你正在閱讀一個緩衝輸入流,但你還寫一個緩衝輸出流?寫作是一種比閱讀更昂貴的操作,對於大型文件來說,你可以做的事情並不多,就像k3b所說的那樣 –

回答

1

我相信,性能不能明顯增加,因爲硬盤/ SD卡的速度可能是瓶頸。

但是,它可能有助於創建複製的後臺任務。

這不是真的快,但因爲你DONOT必須等待複製操作完成後,感覺速度更快。

此解決方案僅適用於您的應用程序在啓動後不需要結果。

詳見AsyncTask

0

transferFrom()必須在循環中調用。它不保證在一次通話中轉移全部金額。

0

我終於做了覆蓋和重命名。使用隨機文件覆蓋前x個字節。然後重命名文件。現在速度更快,並且所有文件的大小都相同。

謝謝。

相關問題