Read Text file in android Example

            Reading a text file is a common functionality in all software's and its the same in case of Android applications also. In this example we will read the text file from res/drawable folder line by line and store it into a string.
Now, lets go ahead and see how to get this done.

Step 1: Copy/Create your text file in res/drawable folder
            For this tutorial I have copy pasted a text file named filetoread.txt into res/drawable folder as shown below. Note, ensure your file name is smallcase else, you will get error.

Directory Structure

Step 2 : Read the text file
             Since we have placed our text file in res/drawable folder, we should use openRawResource() class to read the file, since its a application resource.
InputStream is = this.getResources().openRawResource(R.drawable.filetoread);

Then use BufferedReader class to read the input stream as shown below,
BufferedReader reader = new BufferedReader(new InputStreamReader(is));

Then read the BufferedReader object line by line
while ((data = reader.readLine()) != null)
   sbuffer.append(data + "\n");

Thats it, we are almost done with reading text file in Android.

Step 3 : Display text file content in Toast
             Just display the string buffer in Toast as shown below,
Toast.makeText(getBaseContext(), sbuffer.toString(), Toast.LENGTH_LONG).show();

To summarize, first place the text file in res/drawable folder, then read the file line by line and append the string data to string buffer and display this in a toast that it.
Now run the program, you can see the content of the file in Toast message.

import android.os.Bundle;
import android.view.Menu;
import android.widget.Toast;

public class MainActivity extends Activity {

protected void onCreate(Bundle savedInstanceState) {
String data = "";
StringBuffer sbuffer = new StringBuffer();
InputStream is = this.getResources().openRawResource(
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
if (is != null) {
try {
while ((data = reader.readLine()) != null) {
sbuffer.append(data + "\n");
} catch (IOException e) {
// TODO Auto-generated catch block
Toast.makeText(getBaseContext(), sbuffer.toString(), Toast.LENGTH_LONG)

public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(, menu);
return true;


Source Code of this application



Post a Comment