2011-08-27 32 views
2

我試圖移動原料資源損壞的文件(這是一個zip文件)使用此代碼從應用程序到SD卡:複製資源到SD卡給出的Android

void copyFile() throws IOException { 
    File dest = Environment.getExternalStorageDirectory(); 
    InputStream in = context.getResources().openRawResource(R.raw.file); 
    OutputStream out = new FileOutputStream(dest + "/file.zip"); 

    // Transfer bytes from in to out 
    byte[] buf = new byte[1024]; 
    int len; 
    while ((len = in.read(buf)) > 0) { 
     out.write(buf, 0, len); 
    } 
    in.close(); 
    out.close(); 
} 

然而,當我檢查在SD卡上的文件我收到消息: 「存檔是未知的格式或損壞」

爲什麼該文件未被正確複製?

+0

當創建目標文件時,使用適當的構造函數'new File(dest,「file.zip」)'..是否傳送了整個文件? – dacwe

+0

整個文件正在傳輸,但我注意到SD卡上的文件比資源大一點。另外,我如何使用File()。由於資源正在流式傳輸,我需要編寫緩衝區。 –

回答

2

我做了你的代碼的一些小的修改:

File dest = Environment.getExternalStorageDirectory(); 
InputStream in = context.getResources().openRawResource(R.raw.file); 
// Used the File-constructor 
OutputStream out = new FileOutputStream(new File(dest, "file.zip")); 

// Transfer bytes from in to out 
byte[] buf = new byte[1024]; 
int len; 
try { 
    // A little more explicit 
    while ((len = in.read(buf, 0, buf.length)) != -1){ 
     out.write(buf, 0, len); 
    } 
} finally { 
    // Ensure the Streams are closed: 
    in.close(); 
    out.close(); 
} 

對我來說這一次的工作(不是在Android,但一個正常的計算機上)。我所做的修改如下:

  • 我使用了File-constructor作爲FileOutputStream
  • 我使用了try-catch -block,以確保即使在讀/寫時出現錯誤/異常,Streams也會關閉 。
  • 我使用了更明確的read-method(基本上與您的相同 ),因爲當我告訴他該做什麼時我感覺更好。

正如我上面所說,我在我的電腦上試了一下,它工作。證明:

[[email protected] Downloads]$ md5sum quick_action.zip 
4e45fa08f24e971961dd60c3e81b292d quick_action.zip 
[[email protected] Downloads]$ md5sum quick_action_copy.zip 
4e45fa08f24e971961dd60c3e81b292d quick_action_copy.zip 
+0

完美運作。謝謝。儘管有人使用此代碼,但請注意一點。確保您檢查卡沒有安裝。請按照以下主題了解更多信息和示例代碼:http://comments.gmane.org/gmane.comp.handhelds.android.devel/141016 –