2012-02-17 112 views
5

我試圖從android資源目錄中的原始資源文件中創建一個RandomAccessFile對象,但沒有成功。Android原始資源文件中的RandomAccessFile

我只能從原始資源文件中獲得輸入流對象。

getResources().openRawResource(R.raw.file); 

是否有可能建立從原料資源文件RandomAccessFile的對象或者我需要堅持的InputStream?

+2

我不這麼認爲,因爲資源文件仍將存儲在壓縮APK,所以你的InputStream '重新獲得可能是一個ZipEntryInputStream。而且由於它是壓縮的,你必須將它作爲流讀取。在文件中尋找不同的位置可能不是RandomAccessFile能夠做到的。 – Brigham 2012-02-17 21:10:18

+0

「隨機存取文件」...你說,尋求是不可能的? – fabspro 2012-04-24 12:48:21

+0

您需要將文件複製到SD卡(請參閱http://stackoverflow.com/questions/4447477/android-how-to-copy-files-in-assets-to-sdcard),然後您可以使用RandomAccessFile 。 – ron 2012-05-15 22:22:46

回答

1

這是不可能的前進和回來的輸入流,而不會緩衝到內存之間的一切。這可能是非常昂貴的,而且不是用於讀取具有任意大小的(二進制)文件的可伸縮解決方案。

你是對的:理想情況下,人們會使用RandomAccessFile,但是從資源讀取提供了一個輸入流。上面評論中提到的建議是使用輸入流將文件寫入SD卡,並從那裏隨機訪問文件。你可以考慮將文件寫入到一個臨時目錄,閱讀它,使用後刪除它:

String file = "your_binary_file.bin"; 
AssetFileDescriptor afd = null; 
FileInputStream fis = null; 
File tmpFile = null; 
RandomAccessFile raf = null; 
try { 
    afd = context.getAssets().openFd(file); 
    long len = afd.getLength(); 
    fis = afd.createInputStream(); 
    // We'll create a file in the application's cache directory 
    File dir = context.getCacheDir(); 
    dir.mkdirs(); 
    tmpFile = new File(dir, file); 
    if (tmpFile.exists()) { 
     // Delete the temporary file if it already exists 
     tmpFile.delete(); 
    } 
    FileOutputStream fos = null; 
    try { 
     // Write the asset file to the temporary location 
     fos = new FileOutputStream(tmpFile); 
     byte[] buffer = new byte[1024]; 
     int bufferLen; 
     while ((bufferLen = fis.read(buffer)) != -1) { 
      fos.write(buffer, 0, bufferLen); 
     } 
    } finally { 
     if (fos != null) { 
      try { 
       fos.close(); 
      } catch (IOException e) {} 
     } 
    } 
    // Read the newly created file 
    raf = new RandomAccessFile(tmpFile, "r"); 
    // Read your file here 
} catch (IOException e) { 
    Log.e(TAG, "Failed reading asset", e); 
} finally { 
    if (raf != null) { 
     try { 
      raf.close(); 
     } catch (IOException e) {} 
    } 
    if (fis != null) { 
     try { 
      fis.close(); 
     } catch (IOException e) {} 
    } 
    if (afd != null) { 
     try { 
      afd.close(); 
     } catch (IOException e) {} 
    } 
    // Clean up 
    if (tmpFile != null) { 
     tmpFile.delete(); 
    } 
} 
+3

這真的是唯一的方法嗎?這似乎非常迂迴。沒有辦法簡單地隨機訪問原始目錄中的資源文件? – Fra 2015-05-26 14:48:10