RandomAccessFile in Android Raw File

I tried to create a RandomAccessFile object from a raw resource file in the Android resource directory without success.

I can only get the input object from the raw resource file.

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

Is it possible to create a RandomAccessFile object from a raw resource file, or do I need to stick to the input stream?

+6
source share
2 answers

It is simply not possible to search back and forth in the input stream without buffering everything in memory. This can be extremely costly and not a scalable solution for reading a (binary) file of arbitrary size.

: 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 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();
    }
}
+2

AssetFileDescriptor , ? , ( ?)

//seek to your first start position
InputStream ins = getAssets().openFd("your_file_name").createInputStream();
isChunk.skip(start);
//read some bytes
ins.read(toThisBuffer, 0, length);

//later on
//seek to a different position, need to openFd again! 
//because createInputStream can be called on asset file descriptor only once.
//This resets the new stream to file offset 0, 
//so need to seek (skip()) to a new position relative to file beginning.

ins = getAssets().openFd("your_file_name").createInputStream();
ins.skip(start2);

//read some bytes
ins.read(toThatBuffer, 0, length);

, 20 .

0

All Articles