How to read text file in Android? [duplicate]

I am saving details in out.txt file which has created a text file in data/data/new.android/files/out.txt. I am able to append information to the text, however, I am unable to read this file. I used the following procedures to read the file :

File file = new File( activity.getDir("data", Context.MODE_WORLD_READABLE), "new/android/out.txt");
 BufferedReader br = new BufferedReader(new FileReader(file));

Can anyone please help me out to fix this issue ?

Regards, Sunny.


@hermy's answer uses dataIO.readLine(), which has now deprecated, so alternate solutions to this problem can be found at How can I read a text file in Android?. I personally used @SandipArmalPatil's answer...did exactly as needed.

StringBuilder text = new StringBuilder();
try {
     File sdcard = Environment.getExternalStorageDirectory();
     File file = new File(sdcard,"testFile.txt");

     BufferedReader br = new BufferedReader(new FileReader(file));  
     String line;   
     while ((line = br.readLine()) != null) {
                text.append(line);
                text.append('\n');
     }
     br.close() ;
 }catch (IOException e) {
    e.printStackTrace();           
 }

TextView tv = (TextView)findViewById(R.id.amount);  
tv.setText(text.toString()); ////Set the text to text view.

You can read a line at a time with this:

FileInputStream fis;
final StringBuffer storedString = new StringBuffer();

try {
    fis = openFileInput("out.txt");
    DataInputStream dataIO = new DataInputStream(fis);
    String strLine = null;

    if ((strLine = dataIO.readLine()) != null) {
        storedString.append(strLine);
    }

    dataIO.close();
    fis.close();
}
catch  (Exception e) {  
}

Change the if to while to read it all.


Just put your file (ie. named yourfile) inside the res/raw folder (you can create if if doesn't exist) inside your project. The R.raw.yourfile resource will be automatically generated by the sdk. To obtain a String of the text file, just use the code suggested by Vovodroid in the following post: Android read text raw resource file

 String result;
    try {
        Resources res = getResources();
        InputStream in_s = res.openRawResource(R.raw.yourfile);

        byte[] b = new byte[in_s.available()];
        in_s.read(b);
        result = new String(b);
    } catch (Exception e) {
        // e.printStackTrace();
        result = "Error: can't show file.";
    }