Android – Read text file from SD-card

By -
Problem: How to read simple text file from SD-card?
Description:

First of all, let me give you a link: Environment class and getExternalStorageDirectory() method, through this method we gets the root directory of sd-card, because if we write only “/sdcard” as a static value then there may be a chance of problem because there may be having /mnt/sdcard as a root directory in some of android devices.

Now, we use this method as below:

File dir = Environment.getExternalStorageDirectory();

And the rest of the procedure I have given and described by making comments in the example so now go through the full solutions provided below with the output snap.

Output:
Android - Read text file from SD-Card

Android – Read text file from SD-Card

Solution:

ReadFileSDCardActivity.java

package com.paresh.readfilesdcard;

package com.paresh.readfilesdcard;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;

/**
 * @author Paresh N. Mayani
 * @Website http://www.technotalkative.com
 */

public class ReadFileSDCardActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        //Find the view by its id
        TextView tv = (TextView)findViewById(R.id.fileContent);

        File dir = Environment.getExternalStorageDirectory();
        //File yourFile = new File(dir, "path/to/the/file/inside/the/sdcard.ext");

        //Get the text file
        File file = new File(dir,"text.txt");
        // i have kept text.txt in the sd-card

        if(file.exists())   // check if file exist
        {
        	  //Read text from file
            StringBuilder text = new StringBuilder();

            try {
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;

                while ((line = br.readLine()) != null) {
                    text.append(line);
                    text.append('n');
                }
            }
            catch (IOException e) {
                //You'll need to add proper error handling here
            }
            //Set the text
            tv.setText(text);
        }
        else
        {
        	tv.setText("Sorry file doesn't exist!!");
        }
     }
}

Download Full source code from here: Android – Read text file from SD-Card.

Paresh Mayani

Lazy android developer, exploring the horizon of android development since 5 years. He is Senior Software engineer at InfoStretch Solutions Pvt. Ltd. He is the Head/Organizer of Google Developers Group (GDG), Ahmedabad

Loading Facebook Comments ...
Loading Disqus Comments ...