Working with Text Files in Android


Today we are going to code about a sample app with some operations I usually play with text files in my Android applications. These operations would include creating, reading, updating,and deleting text files. I find these operations really useful when I have to store some data temporarily, creating some log files, or store some actual content just like what evernote does, see screenshot below.

Working with Text Files in Android

For apps like Evernote, storing some user content data on the device disk or sdcard is okay, some reason include, the device is a personal property, it is always with you. Another reason is, the data is “syncable”. If you think you lost some data in the device (like accidental file deletion), you can always simply sync and your data will come back to life in your device. I love cloud computing!
Below is the code download, basic CRUD codes and a Sample Application.

Download code here

Sample Application

txtlayout

In this sample application, when a user clicked a button:

  • Create Text File – a folder in your sdcard will be created with an empty text file in it (sdcard/MikeDalisayFolder/coan_log_file.txt)
  • Read Text File – the contents of coan_log_file.txt text file will be shown in the screen, you should click the update text file button first so it will have contents.
  • Update Text File – it will update our text file with two lines of text.
  • Delete Text File – it will delete our text file, of course. :)
  • We will use a TextFileHelper class I created. I believe you can see more useful techniques here like code re-usability and validation.

src/com.your.package/TextFileHelper.java code – This class contains our text file CRUD codes.

package com.example.textfilesexample;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;

import android.content.Context;
import android.widget.Toast;

/*
 * This class is for text file CRUD.
 * You can just make flashMessage() a comment if you do not need it.
 */
public class TextFileHelper {

    // context is used for toasts
    Context mContext;

    /*
     * Constructor
     */
    public TextFileHelper(Context mContext) {
        this.mContext = mContext;
    }

    /*
     * Create a text file.
     */
    public void createTextFile(String actualFile) {
        try {

            File file = new File(actualFile);

            if (file.exists()) {
                flashMessage(“Text file already exists.”);
            } else {

                // create the text file
                if (file.createNewFile()) {
                    flashMessage(“Text file was created.”);
                } else {
                    flashMessage(“Unable to create text file.”);
                }

            }

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * Read a text file.
     */
    public String readTextFile(String actualFile) {

        String contents = “”;

        try {

            // Get the text file
            File file = new File(actualFile);

            // check if file is not empty
            if (file.exists() && file.length() != 0) {

                // read the file to get contents
                BufferedReader br = new BufferedReader(new FileReader(file));
                String line;

                while ((line = br.readLine()) != null) {
                    // store the text file line to contents variable
                    contents += line + “n“;
                }

            } else {
                flashMessage(“Unable to read. File may be missing or empty.”);
            }

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return contents;
    }

    /*
     * Update a text file.
     */
    public void updateTextFile(String actualFile, String contents) {
        try {

            File textFile = new File(actualFile);

            if (textFile.exists()) {

                // set to true if you want to append contents to text file
                // set to false if you want to remove preivous content of text
                // file
                FileWriter textFileWriter = new FileWriter(textFile, false);

                BufferedWriter out = new BufferedWriter(textFileWriter);

                // create the content string
                String contentString = new String(contents);

                // write the updated content
                out.write(contentString);
                out.close();

                flashMessage(“File was updated.”);

            } else {
                flashMessage(“Cannot update. File does not exist.”);
            }

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * Delete a text file.
     */
    public void deleteTextFile(String actualFile) {
        try {

            File file = new File(actualFile);

            if (file.exists()) {

                if (file.delete()) {
                    flashMessage(“Text file was deleted!”);
                } else {
                    flashMessage(“Unable to delete text file.”);
                }

            } else {
                flashMessage(“Unable to delete. File does not exist.”);
            }

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * Method to create path where our text file will be created.
     */
    public void createPath(String filePath) {
        try {

            File file = new File(filePath);

            if (file.isDirectory()) {
                flashMessage(“Path exists.”);
            }

            // create the directory
            else {
                if (file.mkdirs()) {
                    flashMessage(“Path was created.”);
                } else {
                    flashMessage(“Unable to create path.”);
                }

            }

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * Just an extra method for displaying toasts.
     */
    public void flashMessage(String customText) {
        try {

            Toast.makeText(mContext, customText, Toast.LENGTH_SHORT).show();

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

src/com.your.package/MainActivity.java code

package com.example.textfilesexample;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.TextView;
import android.app.Activity;

public class MainActivity extends Activity {

    // our TextFileHelper
    TextFileHelper TextFileH;

    // where our text file will be created
    String filePath = Environment.getExternalStorageDirectory() + “/MikeDalisayFolder/”;
    
    // name of our text file
    String fileName = “coan_log_file.txt”;
    
    // filePath and fileName combined
    String actualFile = filePath + fileName;
    
    TextView contentsTextView;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        try {

            // initialize our TextFileHelper here
            TextFileH = new TextFileHelper(MainActivity.this);

            // first, make sure the path to your text file is created
            TextFileH.createPath(filePath);
            
            // so we can show file contents to the user
            contentsTextView = (TextView) findViewById(R.id.contentsTextView);
            
            // here is the actual button listener
            View.OnClickListener handler = new View.OnClickListener() {

                public void onClick(View v) {

                    // we will use switch statement and just
                    // get the button’s id to make things easier
                    switch (v.getId()) {

                    // when create button was clicked
                    case R.id.createBtn:
                        TextFileH.createTextFile(actualFile);
                        contentsTextView.setText(“”);
                        break;

                    // when read button was clicked
                    case R.id.readBtn:
                        String contents = TextFileH.readTextFile(actualFile);
                        contentsTextView.setText(contents);
                        break;

                    // when update button was clicked
                    case R.id.updateBtn:
                        TextFileH.updateTextFile(actualFile, “Mike is so handsome!nNew line here!”);
                        contentsTextView.setText(“”);
                        break;

                    // when edit button was clicked
                    case R.id.deleteBtn:
                        TextFileH.deleteTextFile(actualFile);
                        contentsTextView.setText(“”);
                        break;
                    }
                }
            };

            // we will get the button views and set the listener (handler)
            findViewById(R.id.createBtn).setOnClickListener(handler);
            findViewById(R.id.readBtn).setOnClickListener(handler);
            findViewById(R.id.updateBtn).setOnClickListener(handler);
            findViewById(R.id.deleteBtn).setOnClickListener(handler);

        } catch (NullPointerException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

AndroidManifest.xml code – the permission will be WRITE_EXTERNAL_STORAGE

<manifest xmlns:android=“http://schemas.android.com/apk/res/android”
   package=“com.example.textfilesexample”
   android:versionCode=“1″
   android:versionName=“1.0″ >
    <uses-permission android:name=“android.permission.WRITE_EXTERNAL_STORAGE” />
  
    <uses-sdk
       android:minSdkVersion=“8″
       android:targetSdkVersion=“15″ />

    <application
       android:icon=“@drawable/ic_launcher”
       android:label=“@string/app_name”
       android:theme=“@style/AppTheme” >
        <activity
           android:name=“.MainActivity”
           android:label=“@string/title_activity_main” >
            <intent-filter>
                <action android:name=“android.intent.action.MAIN” />

                <category android:name=“android.intent.category.LAUNCHER” />
            </intent-filter>
        </activity>
    </application>

</manifest>

res/layout/activity_main.xml code

<RelativeLayout xmlns:android=“http://schemas.android.com/apk/res/android”
   xmlns:tools=“http://schemas.android.com/tools”
   android:layout_width=“match_parent”
   android:layout_height=“match_parent” >
    <Button
       android:id=“@+id/createBtn”
       android:layout_width=“wrap_content”
       android:layout_height=“wrap_content”
       android:layout_alignParentLeft=“true”
       android:layout_alignParentTop=“true”
       android:text=“Create Text File” />

    <Button
       android:id=“@+id/readBtn”
       android:layout_width=“wrap_content”
       android:layout_height=“wrap_content”
       android:layout_alignParentLeft=“true”
       android:layout_below=“@+id/createBtn”
       android:text=“Read Text File” />

    <Button
       android:id=“@+id/updateBtn”
       android:layout_width=“wrap_content”
       android:layout_height=“wrap_content”
       android:layout_alignParentLeft=“true”
       android:layout_below=“@+id/readBtn”
       android:text=“Update Text File” />

    <Button
       android:id=“@+id/deleteBtn”
       android:layout_width=“wrap_content”
       android:layout_height=“wrap_content”
       android:layout_alignParentLeft=“true”
       android:layout_below=“@+id/updateBtn”
       android:text=“Delete Text File” />

    <TextView
       android:id=“@+id/contentsTextView”
       android:layout_width=“wrap_content”
       android:layout_height=“wrap_content”
       android:layout_alignParentLeft=“true”
       android:layout_below=“@+id/deleteBtn”
       android:text=“Text file contents should be here.” />

</RelativeLayout>

Some other notes:

  • You can create a text file with a different extension name and yet it will still be readable by your program. For example, you can make a file name like “my_file.coan”, evernote does “content.enml”. That file will not be easily read in the device since there are no app that can open a file with that extension. Your text file will be easily ignored by the users.
  • If you want to update a specific line of your text file, you have to read it first, track the line number, insert the updated line and use the code above.

3 responses to “Working with Text Files in Android”

  1. What if I need for example to edit or change a line in the file, UPDATE the text that was previously inserted by another value????

    • Hello @disqus_NIeZER4s0U:disqus, you can scan the previous text file value (using loop), track and update the line you want and then rewrite the value in the text file…

Leave a Reply

Your email address will not be published. Required fields are marked *