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

        android:inputType="textPostalAddress" >

        <requestFocus />

        android:text="TextView" />

        android:text="Save" />

        android:text="View" />

(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 as you can see below. Similarly "ViewText" method also will be written there to view the text saved in the file.
the 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 android.os.Bundle;
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 {

    protected void onCreate(Bundle savedInstanceState) {

     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(;
              String text = ET.getText().toString();

              // close the file


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

catch ( 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('\n');    //to display the text in text line       
             //now we have to surround it with a catch statement for exceptions
            catch (IOException e) {
             //now we assign the text readed to the textview
             TextView tv = (TextView)findViewById(;                         

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(, 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.


  1. Very goood tutorial.

    Please consider add some spaces in the line


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

  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..???

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

  3. Thanks for sharing this useful tutorial.

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

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

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

  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

  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?

  7. very good tutorial, can you mail me the source code to, thanks.

  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.

  9. This is really a very good post
    Android tutorial Read Write text file example kitkat 4.4 with Source code

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

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

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

  13. "Nice message with lots of information included in the posting.Please find our link
    if you may be interested in ,please refer to android app development perth "
    android app development sydney

  14. Excellent tips. Really useful stuff .Never had an idea about this, will look for more of such informative posts from your side... Good job...Keep it up
    android app development sydney | android app developer sydney

  15. You have discussed an interesting topic that every designer to know. Very well explained with examples. Spark interact is recruiting for 2018 check out the great new positions and apply online now Visit web design sydney and upload your resume.

  16. Thank you for your post. This is excellent information. It is amazing and wonderful to visit your site.
    iOS Training
    Apple iOS Training Institutes in Hyderabad

  17. I got such a good information on this topic its very interesting one. You made a good site and I have found a similar website, please check this one Website Designers Sydney
    visit the site to know more.


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.