How to get FileInputStream to File in assets folder
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);
hotHead
Бендерівець by day, android dev by night I don't do m{a,e}th I like d{o,a}gs
Updated on June 12, 2022Comments
-
hotHead about 2 years
I know how to use the
AssetManager
to read aFile
from theres/raw
directory with anInputStream
, but for my special use case I need aFileInputStream
. The reason I need aFileInputStream
specifically is because I need to get theFileChannel
object from it by callinggetChannel()
.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 anUri
, but that just results in aFileNotFoundException
: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 aFile
in theres/raw
directory?