2012-02-17 10 views
5

AndroidリソースディレクトリのrawリソースファイルからRandomAccessFileオブジェクトを作成しようとしましたが、成功しませんでした。AndroidのrawリソースファイルのRandomAccessFile

私はrawリソースファイルからのみ入力ストリームオブジェクトを取得できます。

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

生のアセットファイルからRandomAccessFileオブジェクトを作成することはできますか、または入力ストリームに固執する必要はありますか?

+2

このリソースファイルはまだ圧縮されたAPKに保存されるので、私はそうは思わないので、InputStreamを使用してくださいおそらくZipEntryInputStreamです。圧縮されているので、ストリームとして読み込む必要があります。おそらく、RandomAccessFileが可能なものではありません。 – Brigham

+0

"ランダムアクセスファイル" ...あなたはシークが不可能だと言っていますか? – fabspro

+0

ファイルをSDカードにコピーする必要があります(http://stackoverflow.com/questions/4447477/android-how-to-copy-files-in-assets-to-sdcardを参照)。その後、RandomAccessFileを使用することができます。 – ron

答えて

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

これは本当に唯一の方法ですか?それは非常にロータリーなようです。 rawディレクトリのリソースファイルにランダムアクセスするだけの方法はありませんか? – Fra

関連する問題