Android原始资源文件中的RandomAccessFile

tha*_*van 6 android

我试图从android资源目录中的原始资源文件创建一个RandomAccessFile对象,但没有成功.

我只能从原始资源文件中获取输入流对象.

getResources().openRawResource(R.raw.file);
Run Code Online (Sandbox Code Playgroud)

是否可以从原始资产文件创建RandomAccessFile对象或者我是否需要坚持使用输入流?

Pau*_*sma 2

如果不将中间的所有内容缓冲到内存中,就不可能在输入流中向前和向后搜索。这可能非常昂贵,并且不是用于读取任意大小的(二进制)文件的可扩展解决方案。

你是对的:理想情况下,人们会使用 a 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这真的是唯一的方法吗?看起来非常迂回。有没有办法简单地随机访问原始目录中的资源文件? (3认同)