Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get FileInputStream to File in assets folder

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?

like image 631
hotHead Avatar asked May 20 '15 15:05

hotHead


People also ask

How do you specify a file path in FileInputStream?

This String should contain the path in the file system to where the file to read is located. Here is a code example: String path = "C:\\user\\data\\thefile. txt"; FileInputStream fileInputStream = new FileInputStream(path);

How do I add an asset file?

Step 1: To create an asset folder in Android studio open your project in Android mode first as shown in the below image. Step 2: Go to the app > right-click > New > Folder > Asset Folder and create the asset folder. Step 3: Android Studio will open a dialog box. Keep all the settings default.

Do you need to close a FileInputStream?

Yes, you need to close the inputstream if you want your system resources released back. FileInputStream. close() is what you need.


1 Answers

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);
like image 127
Xaver Kapeller Avatar answered Oct 22 '22 19:10

Xaver Kapeller