Search code examples
androidassetsreadfile

How to open and read a text file in my /assets directory?


I have spent a couple hours reading through the various hits in stackoverflow that result from my title query.

Using Android Studio.

I have a txt file in my src\main\assets project directory that I want to open and read.

All the examples I find use AssetManager() or getAssets() it seems.

I can't get usage of either to work.

InputStreamReader isr = new InputStreamReader(AssetManager.AssetInputStream("xxx.csv"));

Produces error: AssetManager() is not public in AssetManager; cannot be accessed from outside package

What do I need to do to get access to a file in my /assets folder, in order to open and read it?

Edit the problem with marking this as duplicate is that I had read that other post on this same subject, but the users original question (the same I have) is never answered!!! The answer goes about showing the user how to read a file. But the problem was (same as mine): method isn't recognized. In my case (see comment below on answer) I get error: cannot find symbol method getAssets().

Can anyone help me with this? All the examples show the sample code of

AssetManager am = getAssets();

But something is missing.


Solution

  • What you might want to try is use:

    AssetManager am = getAssets();
    InputStream is;
    is = am.open(pathToFile.txt);
    

    Then use a byte[] buffer (get size using is.available(); ) and is.read(buffer) Don't forget to is.close() after read.

    If you're not in an Activity you have to use context.getAssets() in order to get the AssetManager.

    Hope that helps you.