How to Read/Write String from a File in Android?


Introduction

Many times while building an android application we have to store data in the form of files within our android application. We will read and write string data inside our file. In this article we will take a look on How to Read/Write string from a file in Android

Implementation

We will be creating a simple application in which we will be firstly writing the data in that file which the user can enter through edit text. After that we will be reading the data stored in that file by clicking a button and displaying that within our text view.

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.

<?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="match_parent"
   android:layout_height="match_parent"
   tools:context=".MainActivity">
   <!-- creating a text view on below line-->
   <TextView
       android:id="@+id/idTVMessage"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_marginStart="20dp"
       android:layout_marginTop="20dp"
       android:layout_marginEnd="20dp"
       android:layout_marginBottom="20dp"
       android:padding="4dp"
       android:text="Read/Write String from File in Android"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="20sp"
       android:textStyle="bold" />
   <!-- creating an edit text on below line -->
   <EditText
       android:id="@+id/idEdtMsg"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVMessage"
       android:layout_margin="10dp"
       android:hint="Enter message to be saved" />
   <!-- creating a button to write in a file -->
   <Button
       android:id="@+id/idBtnWrite"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idEdtMsg"
       android:layout_marginStart="10dp"
       android:layout_marginTop="10dp"
       android:layout_marginEnd="10dp"
       android:layout_marginBottom="10dp"
       android:text="Write File"
       android:textAllCaps="false" />
   <!-- creating a text view to display the data from a file-->
   <TextView
       android:id="@+id/idTVReadFile"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idBtnWrite"
       android:layout_marginStart="10dp"
       android:layout_marginTop="50dp"
       android:layout_marginEnd="10dp"
       android:layout_marginBottom="10dp"
       android:padding="4dp"
       android:text="File content will appear here"
       android:textAlignment="center"
       android:textColor="@color/black"
       android:textSize="18sp" />
   <!-- creating a button for reading data from a file -->
   <Button
       android:id="@+id/idBtnRead"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:layout_below="@id/idTVReadFile"
       android:layout_marginStart="10dp"
       android:layout_marginTop="10dp"
       android:layout_marginEnd="10dp"
       android:layout_marginBottom="10dp"
       android:text="Read File"
       android:textAllCaps="false" />
</RelativeLayout>

Explanation : In the above code we are creating a root layout as a Relative Layout. Inside this layout we are creating a text view which is used to display the heading of our application. After that we are creating a button which we will use to request permission for reading SMS on mobile devices.

Step 3 : Adding permissions in AndroidManifest.xml file

Navigate to app>AndroidManifest.xml file and add below permissions to it in manifest tag to read sms.

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

Step 4 : Working with MainActivity.java file

Navigate to MainActivity.java. If this file is not visible. To open this file. In the left pane navigate to app>res>layout>MainActivity.java 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.java_test_application;
import android.Manifest;
import android.content.ContextWrapper;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import org.w3c.dom.Text;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.OutputStreamWriter;
public class MainActivity extends AppCompatActivity {
   // creating variables on below line for button.
   private Button readBtn, writeBtn;
   private EditText msgEdt;
   private TextView msgTV;
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      // initializing variables on below line.
      readBtn = findViewById(R.id.idBtnRead);
      writeBtn = findViewById(R.id.idBtnWrite);
      msgEdt = findViewById(R.id.idEdtMsg);
      msgTV = findViewById(R.id.idTVReadFile);
      // on below line adding click listener for short message button.
      readBtn.setOnClickListener(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            // on below line we are checking the self permissions for reading sms.
            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);
            Log.e("TAG", "download is : " + directory.getAbsolutePath() + "
" + directory); 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 below line setting string from file to our text view. msgTV.setText(text); Toast.makeText(contextWrapper, "File read successful..", Toast.LENGTH_SHORT).show(); } }); writeBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // on below line getting data from our edit text. String text = msgEdt.getText().toString(); // on below line validating if edit text is empty or not. if (text.isEmpty()) { Toast.makeText(MainActivity.this, "Please enter the data to be saved..", Toast.LENGTH_SHORT).show(); return; } // on below line creating and initializing 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); // on below line creating a text file. File txtFile = new File(directory, "file" + ".txt"); // on below line writing the text to our file. FileOutputStream fos = null; try { fos = new FileOutputStream(txtFile); OutputStreamWriter osw = new OutputStreamWriter(fos); osw.write(text); osw.flush(); osw.close(); fos.close(); Toast.makeText(contextWrapper, "File write successful..", Toast.LENGTH_SHORT).show(); msgEdt.setText(""); } catch (Exception e) { // on below line handling the exception. e.printStackTrace(); } } }); } }

Explanation − In the above code firstly we are creating variables for a text view and a button and an edit text. 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. Inside the onCreate method we are initializing the variables for button, edit text and text view with the ids which we have given within our activity_main.xml file. After that we are adding a click listener for the read button. Inside the onclick listener we are reading data from a file and setting that in a text view.

After that we are adding an on click listner for our write button. Inside this method we are writing the data to our file from the input entered by the user in the dit text field.

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 article we have taken a look on How to Read/Write the String from a File in Android.

Updated on: 09-May-2023

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements