How can I read a text file from the SD card in Android?
Asked Answered
T

7

69

I am new to Android development.

I need to read a text file from the SD card and display that text file. Is there any way to view a text file directly in Android or else how can I read and display the contents of a text file?

Tradesman answered 25/5, 2010 at 7:12 Comment(1)
do you want to know how to write a program that reads a txt file or do you want to know how to do it as a user?Emma
C
128

In your layout you'll need something to display the text. A TextView is the obvious choice. So you'll have something like this:

<TextView 
    android:id="@+id/text_view" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent"/>

And your code will look like this:

//Find the directory for the SD Card using the API
//*Don't* hardcode "/sdcard"
File sdcard = Environment.getExternalStorageDirectory();

//Get the text file
File file = new File(sdcard,"file.txt");

//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');
    }
    br.close();
}
catch (IOException e) {
    //You'll need to add proper error handling here
}

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

//Set the text
tv.setText(text);

This could go in the onCreate() method of your Activity, or somewhere else depending on just what it is you want to do.

Catchpole answered 25/5, 2010 at 9:27 Comment(5)
@Android Developer - In the sample code it says "You'll need to add proper error handling here". Did you do that because that's probably the mostly like place you'll find your problem.Catchpole
@Dave Webb sorry for the not update my comment. it works for me also. Actually when i put the file in the DDMS then it will clear all the data from the file thats why it returns null at my end.Illmannered
Will this work using a shared network file? I want to file a file in a shared file over the internet, the would the file directory look like, "192.168.197.84/hdd1", "ActivityLog.txt"Brenan
Thank you very much Dave , could u please also show how to read wave/mp3 files as well into a byte array.Kb
@DaveWebb: you should also add uses permission : READ_EXTERNAL_STORAGE in your manifest fileSpanking
V
8

In response to

Don't hardcode /sdcard/

Sometimes we HAVE TO hardcode it as in some phone models the API method returns the internal phone memory.

Known types: HTC One X and Samsung S3.

Environment.getExternalStorageDirectory().getAbsolutePath() gives a different path - Android

Vickey answered 21/6, 2013 at 6:16 Comment(1)
for me it gives some security agumentation junk /com.app.name/data/sdcard/ ... be aware. for logs for myself i hard code it at last it works.Coat
A
3

You should have READ_EXTERNAL_STORAGE permission for reading sdcard. Add permission in manifest.xml

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

From android 6.0 or higher, your app must ask user to grant the dangerous permissions at runtime. Please refer this link Permissions overview

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 0);
    }
}
Audiometer answered 21/8, 2018 at 9:23 Comment(1)
Permissions are the clue when above 6.0. Thanks!Latvian
J
2
package com.example.readfilefromexternalresource;

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

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.Bundle;
import android.os.Environment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;

public class MainActivity extends Activity {
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        textView = (TextView)findViewById(R.id.textView);
        String state = Environment.getExternalStorageState();

        if (!(state.equals(Environment.MEDIA_MOUNTED))) {
            Toast.makeText(this, "There is no any sd card", Toast.LENGTH_LONG).show();


        } else {
            BufferedReader reader = null;
            try {
                Toast.makeText(this, "Sd card available", Toast.LENGTH_LONG).show();
                File file = Environment.getExternalStorageDirectory();
                File textFile = new File(file.getAbsolutePath()+File.separator + "chapter.xml");
                reader = new BufferedReader(new FileReader(textFile));
                StringBuilder textBuilder = new StringBuilder();
                String line;
                while((line = reader.readLine()) != null) {
                    textBuilder.append(line);
                    textBuilder.append("\n");

                }
                textView.setText(textBuilder);

            } catch (FileNotFoundException e) {
                // TODO: handle exception
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            finally{
                if(reader != null){
                    try {
                        reader.close();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                }
            }

        }
    }
}
Jameyjami answered 7/8, 2014 at 6:4 Comment(0)
C
1
BufferedReader br = null;
try {
        String fpath = Environment.getExternalStorageDirectory() + <your file name>;
        try {
            br = new BufferedReader(new FileReader(fpath));
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        }
        String line = "";
        while ((line = br.readLine()) != null) {
         //Do something here 
        }
Chura answered 13/5, 2015 at 11:11 Comment(1)
Can you provide an explanation to your code please.. like where to use it, why does that do the job, etc.Guadalupeguadeloupe
D
1

Beware: some phones have 2 sdcards , an internal fixed one and a removable card. You can find the name of the last one via a standard app:"Mijn Bestanden" ( in English: "MyFiles" ? ) When I open this app (item:all files) the path of the open folder is "/sdcard" ,scrolling down there is an entry "external-sd" , clicking this opens the folder "/sdcard/external_sd/" . Suppose I want to open a text-file "MyBooks.txt" I would use something as :

   String Filename = "/mnt/sdcard/external_sd/MyBooks.txt" ;
   File file = new File(fname);...etc...
Drumlin answered 14/10, 2017 at 8:53 Comment(0)
T
0

All of these answers are unfortunately useless, because outdated since Android 11 (API 30). Due to Google policy, that I do not appreciate, file access to internal or SD card is since then strictly limited in a way that is not really sensible:

  1. You may use SAF mechanism to open directories or single files. Note that SAF is Google proprietary, not supported even by some Android parts, e.g. SQL, and it is extremely slow, about factor 1/20 down to 1/100. This will also work with Android 7 etc..
  2. You may request for MANAGE_EXTERNAL_STORAGE permission. This works with Android 11 and newer, but you will not be allowed to publish your program in Play Store, unless you pretend it's a file manager.
  3. If your program requests READ_EXTERNAL_STORAGE or its Android 13 (API 33) pendants READ_MEDIA_*, you will not and never be able to access text or database files, only audio, movies or images. For whatever reason. So do not try it or use it as fallback for Android versions up to 10.
Traction answered 12/9, 2023 at 11:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.