Reading a simple text file

Dalvinder Singh picture Dalvinder Singh · Apr 24, 2011 · Viewed 210.5k times · Source

I am trying to read a simple text file in my sample Android Application. I am using the below written code for reading the simple text file.

InputStream inputStream = openFileInput("test.txt");
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

My questions is : Where should I place this "test.txt" file in my project?. I have tried putting the file under "res/raw" and "asset" folder but I get the exception "FileNotFound" when first live of the code written above gets executed.

Thanks for the help

Answer

shihpeng picture shihpeng · Apr 24, 2011

Place your text file in the /assets directory under the Android project. Use AssetManager class to access it.

AssetManager am = context.getAssets();
InputStream is = am.open("test.txt");

Or you can also put the file in the /res/raw directory, where the file will be indexed and is accessible by an id in the R file:

InputStream is = context.getResources().openRawResource(R.raw.test);