How to read and write a text file that is stored in your application sandbox in ANDROID?

By | April 22, 2012

Hi all…..

In this post I will show you how to read a text file in ANDOID.
Let your file is in the your application sandbox of your ANDOID project, i.e the file’s location is /data/data/your_package_name folder.
To view this folder -> open File Explorer and expand each folder.
For this example to work first push te file into this folder, because I am not creating it now.
The file is named “myfile.txt”

This example reads the file line by line using readLine() function till the end of the file. Here your need two classes named “InputStreamReader” and “BufferedReader”. For writing into the file you need “OutputStreamReader” class. The result is displayed in a Toast. Make sure you notice it.

The following is the code for reading the text file………

String     res  =    null;
try {

	   InputStream       in = openFileInput("myfile.txt");

	   if (in != null) {
	    // prepare the file for reading
	     InputStreamReader input = new InputStreamReader(in);
	     BufferedReader buffreader = new BufferedReader(input);

	      res = "";
	      while (( line = buffreader.readLine()) != null) {
	      	res += line;
	      }
	      in.close();
	      Toast.makeText(getApplicationContext(),"File Contents ==> " + res,Toast.LENGTH_SHORT).show();
          }else{
	    }

} catch(Exception e){
       Toast.makeText(getApplicationContext(),     e.toString() +   e.getMessage(),Toast.LENGTH_SHORT).show();
}

Want More then

Follow this link

How to read and write files to SDCARD and application SandBox in Android – A complete example?

Please leave your comments on this post.

5 thoughts on “How to read and write a text file that is stored in your application sandbox in ANDROID?

  1. Veselin

    Hi,

    If the file is in assets folder it must be read with:
    // InputStream in = openFileInput(“myfile.txt”);
    InputStream in = getAssets().open(“myfile.txt”);

    openFileInput is for file in
    /data/data/com.some_dev.some_app/files
    folder (can be seen on rooted devices).

    Best Regards

    Reply
  2. Karthik

    Hey,
    this code doesnt really work. because I only get null printed on my screen.

    Even Veselin’s info wasnt good enough to make it work… See any bug in the code?

    Reply
    1. James

      Hey Karthik :- check your File explorer if the file has been created or not. This code is perfectly working.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *