How to get FileInputStream to File in assets folder

旧巷老猫 提交于 2019-12-18 02:46:31

问题


I know how to use the AssetManager to read a File from the res/raw directory with an InputStream, but for my special use case I need a FileInputStream. The reason I need a FileInputStream specifically is because I need to get the FileChannel object from it by calling getChannel().

This is the code I have so far, it reads the data (in my case a list of primitives) from a File:

public static int[] loadByMappedBuffer(Context context, String filename) throws IOException{
    FileInputStream fis = context.openFileInput(filename);
    FileChannel ch = fis.getChannel();

    MappedByteBuffer mbuff = ch.map(MapMode.READ_ONLY, 0, ch.size());
    IntBuffer ibuff = mbuff.asIntBuffer();

    int[] array = new int[ibuff.limit()];
    ibuff.get(array);

    fis.close();
    ch.close();

    return array;
} 

I had tried to create File from an Uri, but that just results in a FileNotFoundException:

Uri uri = Uri.parse("android.resource://com.example.empty/raw/file");
File file = new File(uri.getPath());
FileInputStream fis = new FileInputStream(file);

Is there a way I can get a FileInputStream to a File in the res/raw directory?


回答1:


You can get a FileInputStream to a resource in your assets like this:

AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
FileInputStream stream = fileDescriptor.createInputStream();

The fileName you supply to openFd() should be the relative path to the asset, the same fileName you would supply to open().

Alternatively you can also create the FileInputStream like this:

AssetFileDescriptor assetFileDescriptor = assetManager.openFd(fileName);  
FileDescriptor fileDescriptor = assetFileDescriptor.getFileDescriptor();  
FileInputStream stream = new FileInputStream(fileDescriptor);


来源:https://stackoverflow.com/questions/30354120/how-to-get-fileinputstream-to-file-in-assets-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!