2012-06-07 29 views

回答

5

這裏是我做過什麼:

複製你的資產文件到SD卡:

AssetManager assetManager = context.getResources().getAssets(); 

String[] files = null; 

try { 
    files = assetManager.list("ringtone"); //ringtone is folder name 
} catch (Exception e) { 
    Log.e(LOG_TAG, "ERROR: " + e.toString()); 
} 

for (int i = 0; i < files.length; i++) { 
    InputStream in = null; 
    OutputStream out = null; 
    try { 
     in = assetManager.open("ringtone/" + files[i]); 
     out = new FileOutputStream(basepath + "/ringtone/" + files[i]); 

     byte[] buffer = new byte[65536 * 2]; 
     int read; 
     while ((read = in.read(buffer)) != -1) { 
      out.write(buffer, 0, read); 
     } 
     in.close(); 
     in = null; 
     out.flush(); 
     out.close(); 
     out = null; 
     Log.d(LOG_TAG, "Ringtone File Copied in SD Card"); 
    } catch (Exception e) { 
     Log.e(LOG_TAG, "ERROR: " + e.toString()); 
    } 
} 

的路徑然後閱讀您的文件:

File ringFile = new File(Environment.getExternalStorageDirectory().toString() + "/ringtone", "fileName.mp3"); 

你去那裏。你有你的資產文件的文件對象的副本。希望這可以幫助。

+0

如果我喜歡這個,我會在應用程序中感受到內存不足。 – Pavandroid

+0

這是爲我工作。我省略了一些部分。在此代碼之前,請使用文件對象的mkdirs()方法創建文件夾。你可以谷歌它。 – drulabs

+0

您正在爲@ vipul's和我的解決方案解決內存異常......您可以粘貼logcat條目。有些事情是不對的。你在設備或模擬器上測試? – drulabs

0

我不知道有什麼方法可以得到一個實際File對象,但如果你能有一個FileDescriptor工作,你可以這樣做:

FileDescriptor fd = getAssets().openFd(assetFileName).getFileDescriptor(); 
+2

我不知道這可以用什麼方式。你能解釋一下這個描述符的用法嗎? – Pavandroid

4

讀取原始文件到文件。

InputStream ins = getResources().openRawResource(R.raw.my_db_file); 
    ByteArrayOutputStream outputStream=new ByteArrayOutputStream(); 
    int size = 0; 
    // Read the entire resource into a local byte buffer. 
    byte[] buffer = new byte[1024]; 
    while((size=ins.read(buffer,0,1024))>=0){ 
     outputStream.write(buffer,0,size); 
    } 
    ins.close(); 
    buffer=outputStream.toByteArray(); 

    FileOutputStream fos = new FileOutputStream("mycopy.db"); 
    fos.write(buffer); 
    fos.close(); 

爲了避免內存不足應用以下邏輯。

不要創建一個包含所有數據的巨大ByteBuffer。創建一個小得多的ByteBuffer,填充數據,然後將這些數據寫入FileChannel。然後重置ByteBuffer並繼續,直到寫入所有數據。

+0

如果我喜歡這樣,我會在應用程序中感受到內存不足。 – Pavandroid

+0

查看更新的答案 –

+0

感謝您的解決方案。爲你+1。乾杯。 –