Saturday, February 2, 2013

9.How to write and read from a text file in Android

Today we are going to learn how to read and write from a text file(Sorce file download link given at the end). The text file can be created in the internal memory or external memory (SD Card).
 (TIP) but you cannot write in to a file which is in the application directory like asset folder, since all application files will be read only when the application is run.

Now we want an Edit Text, a TextView and two buttons for this activity. What we enter in EditText will be saved when clicking a button "Save" and will be read and displayed in TextView when we click "ViewText" button.

So the Activity_Main XML file will be looked as follows.

<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"
    tools:context=".MainActivity" >

   
    <EditText
        android:id="@+id/editText1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"       
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:ems="10"
        android:inputType="textPostalAddress" >

        <requestFocus />
    </EditText>

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"       
        android:layout_below="@+id/editText1"
        android:layout_centerHorizontal="true"       
        android:text="TextView" />
   
     <LinearLayout
         android:layout_width="fill_parent"
         android:layout_height="wrap_content"
         android:layout_alignParentBottom="true"
         android:layout_marginBottom="30dp"
         android:gravity="center">

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"       
        android:onClick="SaveText"
        android:text="Save" />

    <Button
        android:id="@+id/button2"
        android:layout_marginLeft="20dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="ViewText"
        android:text="View" />
   
     </LinearLayout>
</RelativeLayout>


(TIP) I have created the two buttons inside a LinearLayout and given the gravity as center. So that both the buttons will be automatically aligned center. On the second button I have given a margin to the left side so that it will be separated from the first button by 20dp.

When the button1 (will be displayed as "view" button since the button text is view) is clicked a method "SaveText" will be called to save the text in to a file. ( that is why we have given here onClick="SaveText") This "SaveText" method will be written  in MainActivity.java as you can see below. Similarly "ViewText" method also will be written there to view the text saved in the file.
the MainActivity.java will be as follows.

for easy to understand I have given all the activities as comments (anything start with "//" is a comment)

package com.arise.filewritereader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

   
     public void SaveText(View view){   
       
         try {


              // open myfilename.txt for writing
              OutputStreamWriter out=newOutputStreamWriter(openFileOutput("myfilename.txt",MODE_APPEND));
              // write the contents to the file


              EditText ET = (EditText)findViewById(R.id.editText1);
              String text = ET.getText().toString();
               out.write(text);
               out.write('\n');   

           
              // close the file


              out.close();


              Toast.makeText(this,"Text Saved !",Toast.LENGTH_LONG).show();
            } 


catch (java.io.IOException e) {

              //do something if an IOException occurs.

Toast.makeText(this,"Sorry Text could't be added",Toast.LENGTH_LONG).show();


            }
               
     }

   
     public void ViewText (View view){   
       
     StringBuilder text = new StringBuilder();
   
   
     try {
            // open the file for reading we have to surround it with a try
       
            InputStream instream = openFileInput("myfilename.txt");//open the text file for reading
           
            // if file the available for reading
            if (instream != null) {               
               
              // prepare the file for reading
              InputStreamReader inputreader = new InputStreamReader(instream);
              BufferedReader buffreader = new BufferedReader(inputreader);
              
              String line=null;
              //We initialize a string "line"
             
            while (( line = buffreader.readLine()) != null) {
                //buffered reader reads only one line at a time, hence we give a while loop to read all till the text is null
                                       
                            text.append(line);   
                            text.append('\n');    //to display the text in text line       
           
                   
              }}}   
               
             //now we have to surround it with a catch statement for exceptions
            catch (IOException e) {
                e.printStackTrace();
            }
   
             //now we assign the text readed to the textview
             TextView tv = (TextView)findViewById(R.id.textView1);                         
             tv.setText(text);        
            
        }

     
   
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }

}



what we are doing is when first button (named "Save") is clicked first  method ie. "SaveText" will be called. I have highlighted it as red. OutputStreamWriter is used to write in to file. The file named "myfilename.txt" will be automatically created in the internal phone memory when it is called for writing. Here we give "MODE_APPEND" so that what ever the text added in to the file will be appended in to the existing one. If "0" is given instead of "MODE_APPEND" it will re write all the data in the file.

Now we find the EditText1 as given in the XML file and give it a name "ET" then we create a string called "text" and save what ever you enter in the EditText in to it. Now we write the contents saved in the String named "text" in the file using a command "out.write()". Since it is append mode, it will write the text you enter next time in to the same line with out any space or comma. So we use out.write('\n'); so that next line will be saved below the first line. Then we close the file, toast something and surround it with a catch statement to handle exceptions.

When the "View" button is clicked the  second method is executed. I have given it as blue. We will open the same file for reading and read the content with a BufferedReader. But it can only read one line at a time. So we give a while loop to read all lines till the line is null. The readed line will be stored in a String called "line" and it will be appended to a StringBuilder called "text" which was initialised just after calling method.


Now we find the TextView in the XML file and give it  a name "tv" and the "text" will be set in to the TextView.


When we run the emulator we can write something in the EditText and click the "Save" button to write in to the file as follows.



Now when we click the "View" button, the text saved in the file will be read and shown in to the TextView as follows.

So, Today we have learned how to write and read from a Text File. Thank you for reading.
(TIP) You may download the full source file from here.

18 comments:

  1. Very goood tutorial.

    Please consider add some spaces in the line

    OutputStreamWriterout=newOutputStreamWriter(openFileOutput("myfilename.txt",MODE_APPEND));

    correct:
    OutputStreamWriter out=new OutputStreamWriter(openFileOutput("myfilename.txt",MODE_APPEND));

    ReplyDelete
  2. Can i use the sane code if the text file is on cloud drive... eg dropbox or something....Will d text file get open if i give the link to that file..???

    ReplyDelete
    Replies
    1. No. If you use this code the text file will be written in the phone memory and read from there.

      Delete
  3. Thanks for sharing this useful tutorial.

    Where the directory files of the Android phone that contain the "myfilename.txt"?

    ReplyDelete
    Replies
    1. You cannot access the file in your device. it will be written in phone memory

      Delete
  4. EditText ET = (EditText)findViewById(R.id.editText1); it says " editText1 cannot be resolved or is not a field "
    Same goes for TextView tv = (TextView)findViewById(R.id.textView1); "textView1 cannot be resolved.... etc."
    getMenuInflater().inflate(R.menu.activity_main, menu); " acitvity_main cannot be resolved...etc"
    What did I do wrong?

    ReplyDelete
  5. Hello to every one, it's actually a nice for me to pay a quick visit this web site, it consists of useful Information.
    website design

    ReplyDelete
  6. Thanks for the demo. It works fine. But I wonder where did you put your onClickListener code for the 2 buttons..? Silly question, right?

    ReplyDelete
  7. very good tutorial, can you mail me the source code to n.sarin@yahoo.com, thanks.

    ReplyDelete
  8. Hello Sir, I'm new to Android Development. And so I want your help in this regard. I searched a lot for creating and reading text file in Android but couldn't find any nice help. But at last I came to your's this tutorial. It is EXCELLENT . Thanks for this.
    But I'm still in a confusion / problem , that I can't find this text file "myfilename.txt". Will you pleeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeaaaaseeeeeeee help me out???? You have written here "internal storage". But I even searched using Root Browsers, but to no avail. Please tell me where the file is. Or please direct me to some of your tutorial that let user create text file on SDCard or some other browsable location.

    ReplyDelete
  9. This is really a very good post http://www.androidinterview.com/android-internal-storage-read-and-write-text-file-example/
    Android tutorial Read Write text file example kitkat 4.4 with Source code

    ReplyDelete
  10. Can you put the save button as a menu item?

    ReplyDelete
  11. the files are host in /data/data/PACKAGE_NAME/files/filename.txt you need root access to get in to there

    ReplyDelete
  12. the files are host in /data/data/PACKAGE_NAME/files/filename.txt you need root access to get in to there

    ReplyDelete

Please give your valuable comments so as to know whether this blog is useful to you.You can also write helpful Android Development Syntax or Shortcuts or Tips.