Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read text file in Android? [duplicate]

Tags:

android

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.

like image 496
sunny Avatar asked Jul 27 '10 14:07

sunny


People also ask

How to copy code in Android studio?

To copy data, you create an Intent, put it into a clip object, and put the clip object onto the clipboard. To paste the data, you get the clip object and then copy the Intent object into your application's memory area.


2 Answers

@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.
like image 179
user1135469 Avatar answered Nov 14 '22 21:11

user1135469


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.

like image 20
hermy Avatar answered Nov 14 '22 20:11

hermy