How to read a text file from the SD card in Android?


Introduction

Many times in android applications we have to download a specific file and we store that file in our device's external storage. Sometimes we have to access these files fromour devices external storage and display the content from these files within our android application. In this article we will take a look at How to read a text file from the SD Card in android.

Implementation

We will be creating a simple application in which we will be displaying two text views. In the first text view we will be displaying the heading for our application and in the second text view we will be displaying a message to be read from our file which is stored in the external storage.

Step 1 : Creating a new project in Android Studio

Navigate to Android studio as shown in below screen. In the below screen click on New Project to create a new Android Studio Project.

After clicking on New Project you will get to see the below screen.

Inside this screen we have to simply select Empty Activity and click on Next. After clicking on next you will get to see the screen below.

Inside this screen we have to simply specify the project name. Then the package name will be generated automatically.

Note − Make sure to select the Language as Java.

After specifying all the details click on Finish to create a new Android studio project.

Once our project has been created we will get to see 2 files which are open i.e activity_main.xml and MainActivity.java file.

Step 2 : Working with activity_main.xml.

Navigate to activity_main.xml. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>activity_main.xml to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

Syntax

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical"
   tools:context=".MainActivity">

   <!-- on below line creating a text view for displaying a heading-->
   <TextView
      android:id="@+id/idTVHeading"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_above="@id/idTVMsg"
      android:layout_margin="10dp"
      android:padding="4dp"
      android:text="How to read a text file from the SD card in Android?"
      android:textAlignment="center"
      android:textColor="@color/black"
      android:textSize="20sp"
      android:textStyle="bold" />

   <!-- on below line creating a text view for displaying a message from our file-->
   <TextView
      android:id="@+id/idTVMsg"
      android:layout_width="match_parent"
      android:layout_height="wrap_content"
      android:layout_centerInParent="true"
      android:text="Message"
      android:textAlignment="center"
      android:textColor="@color/black"
      android:textSize="18sp" />
</RelativeLayout>

Explanation − In the above code the root element is a Relative layout in android. This layout is a view group which is used to align all the elements within it relative to each other. We can relatively align all elements within Relative Layout with the help of ids or positions.

Inside this relative layout we are creating two text views. In the first text view we are displaying the heading for our application whereas in the second text view we will be displaying the text from our file in the external storage.

At last we are adding a closing tag for our Relative Layout as the text view and button is enclosed in our relative layout.

Step 3 : Adding file read permissions in AndroidManifest.xml file to read files from External Storage.

Navigate to app>manifests>AndroidManifest.xml file and add internet permissions to it in the manifest tag.

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

Explanation − As we are opening our file from external storage we have to provide the read external storage inside our AndroidManifest.xml file.

Step 4 : Working with MainActivity.java.

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>java>your app’s package name>MainActivity.kt to open this file. After opening this file. Add the below code to it. Comments are added in the code to get to know in detail.

package com.example.androidjavaapp;

import androidx.appcompat.app.AppCompatActivity;
import android.content.ContextWrapper;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class MainActivity extends AppCompatActivity {
   // on below line creating a variables
   private TextView msgTV;

   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      // on below line initializing web view with id.
      msgTV = findViewById(R.id.idTVMsg);

      // on below line creating a variable for context wrapper.
      ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
      // on below line creating a directory for file and specifying the file name.
      File directory = contextWrapper.getExternalFilesDir(Environment.DIRECTORY_DOWNLOADS);
      File txtFile = new File(directory, "file" + ".txt");
      // on below line creating a string builder.
      StringBuilder text = new StringBuilder();
      try {
         // on below line creating and initializing buffer reader.
         BufferedReader br = new BufferedReader(new FileReader(txtFile));
         // on below line creating a string variable/
         String line;
         // on below line setting the data to text
         while ((line = br.readLine()) != null) {
            text.append(line);
            text.append('
'); } br.close(); // on below line handling the exception } catch (Exception e) { Toast.makeText(getApplicationContext(), "Fail to read the file..", Toast.LENGTH_SHORT).show(); } // on the below line setting data to our text view. msgTV.setText(text); } }

Explanation − In the above code for the MainActivity.java file. Firstly we are creating a variable for the text view.

Now we will get to see the onCreate method. This is the default method of every android application. This method is called when the application view is created. Inside this method we are setting the content view i.e the layout file named activity_main.xml to set the UI from that file.

After specifying the view we are initializing our TextView variable named as msgTV with its unique id which we have given in the activity_main.xml file.

After initializing our text view we are creating a variable for our file to read from the file path and we are specifying the file name as file.txt. Make sure to change the file name according to the file which you have stored inside the device. Then we are creating a string builder which is used to read the data from that file.

At last we are setting the text which we have read from our file inside our msgTV by calling set text method.

After adding the above code now we have to simply click on the green icon in the top bar to run our application on a mobile device.

Note − Make sure you are connected to your real device or emulator.

Output

Conclusion

In the above tutorial we have learned how to read the data from a text file which is stored in the external storage.

Updated on: 30-Mar-2023

917 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements