Quantcast
Viewing latest article 1
Browse Latest Browse All 2

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

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.


Viewing latest article 1
Browse Latest Browse All 2

Trending Articles