mathmax mathmax - 1 year ago 169
Java Question

Android: load from resource file

I would like to use a Java library in my Android application. The class constructors and methods of this library often take paths to files (configuration file, dictionary, etc.) and then build instances based on the given paths.

In my android application, I would like to store these file in the 'res' folder (possibly in res/raw). The problem is that I have to give a path to these files to the methods of the library.

I could easily get an InputStream using getResources(), but this would not be directly usable by my library. I would have to go through all the methods taking a path as an argument, replace it by an InputStream and modify the content to deal with InputStreams instead of Files. This represent quite a lot of work and I would much prefer to use the library without modification and keep it easily upgradable.

Even though using based on resource file would not be a good practice, is it something possible? It would definitely help if you could indicate a way to do this.

Thank you.

Answer Source

If the library uses then I don't think there is a way to do this in Java (let alone the Android subset of Java). It might be possible to solve the problem with a loopback filesystem, but this depends on your Android device's kernel, etc.


If the library uses java.nio.file.Path, then it may be possible to implement a custom FileSystemProvider that maps the resources into the default file system namespace.

Note this is for regular Java 7. It would require a back-port of the relevant NIO libraries to get this to work on Android. I had another look for a viable backport, and couldn't find one.


There is another "clunky" way to do this. Get your application to copy the relevant resources to files that can be accessed via a File.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download