Search code examples
androidfile-ioandroid-resourcesioexceptionmat-file

How to load *.mat file in raw folder of android


I try to load a .mat file in Android 4.4, using JMatIO.

It worked well when the .mat file was in external storage, but it didn't work when the file was in the app's raw folder. Currently, the application can not find any *.mat files. The log just prints the message, "fail to load matrix file".

Below is the code I'm using:

try {
        mfr = new MatFileReader("android.resource://" + getPackageName() + "/raw/rm.mat");
} catch (IOException e) {
        e.printStackTrace();
        Log.d(TAG, "fail to load matrix file");
        System.exit(0);
}
if (mfr != null) {
        Log.d(TAG, "Success to load matrix file");
}

How can I load the file successfully?


Solution

  • It looks like you're not accessing the file properly with this code:

    mfr = new MatFileReader("android.resource://" + getPackageName() + "/raw/rm.mat");
    

    From what I understand, you're trying to access a file which is located in you \res\raw\ folder. This is usually done using R.raw.filname_without_extension. In your case you should try:

    mfr = new MatFileReader(getResources().openRawResource(R.raw.rm), MatFileType.Regular);
    

    If you are still having problems, take a look at these resources:

    1. Documentation: Accessing Resources

      Access to Original Files

      While uncommon, you might need access your original files and directories. If you do, then saving your files in res/ won't work for you, because the only way to read a resource from res/ is with the resource ID. Instead, you can save your resources in the assets/ directory.

      Files saved in the assets/ directory are not given a resource ID, so you can't reference them through the R class or from XML resources. Instead, you can query files in the assets/ directory like a normal file system and read raw data using AssetManager.

      However, if all you require is the ability to read raw data (such as a video or audio file), then save the file in the res/raw/ directory and read a stream of bytes using openRawResource()

    2. JMatIO Source: The relevant MatFileReader signature

    3. SO Question: R.raw.anything cannot be resolved
    4. SO Question: How to get File from R.raw
    5. SO Question: How to read file from res/raw by name