Cubbi
Cubbi

Reputation: 9

How can I import, and use txt file in Android Studio?

I've tried, searched a lot of things here, but non of those seem to work. (The file has 5000 rows) I keep getting error massages. For example with AssetManager: Cannot resolve method 'getAssets()' -> and in the code getAssets is red.

private static InputStream getReadTextFromAssets() throws IOException {
    AssetManager assetManager = getAssets();
    InputStream file = assetManager.open("tryToRead.txt");
    return file;
}

Upvotes: 0

Views: 535

Answers (2)

Yazan
Yazan

Reputation: 6082

Method getAssets() is accessable via instance of Resources class,

pass that as argument to your method:

private static InputStream getReadTextFromAssets(Resources myRes) throws IOException {}

and use it to call getAssets()

myRes.getAssets()

and for using your method, pass Resources when invoking method

InputStram is = getReadTextFromAssets(getResources());

Again, getResources() needs Context class [Activity] or an instance of Context obtained from an Activity.

Upvotes: 0

Mohammad Tauqir
Mohammad Tauqir

Reputation: 1815

I had the same problem for getting files from assets folder. So instead I created a raw folder inside res directory, then copied my files insideraw folder. Now getting the files from raw folder was very easy. See below link

How to read file from res/raw by name

You can also see below link if you want to stick with asset folder.

How to reference a File in raw folder in Android

Upvotes: 1

Related Questions