How to Read and Write from a File in Android?

Here is source code of the Program to Demonstrate Reading and Writing to a File in Android. The program is successfully compiled and run on a Windows system using Eclipse Ide. The program output is also shown below.

MainActivity.java

package com.example.readwrite_file;
 
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
 
public class MainActivity extends Activity {
 
    private static final String TAG = MainActivity.class.getName();
    private static final String FILENAME = "myFile.txt";
 
    TextView text;
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 
        text = (TextView) findViewById(R.id.textView1);
 
        Button Read = (Button) findViewById(R.id.read);
        Button write = (Button) findViewById(R.id.writefile);
 
        Read.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                readFromFile();
                Toast.makeText(getApplicationContext(),
                        "Successfully read From file", Toast.LENGTH_SHORT)
                        .show();
            }
        });
        final String textToSaveString = "Hello Android";
 
        write.setOnClickListener(new View.OnClickListener() {
 
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                writeToFile(textToSaveString);
                Toast.makeText(getApplicationContext(), "Write made to file",
                        Toast.LENGTH_SHORT).show();
 
            }
        });
 
    }
 
    private void writeToFile(String data) {
        try {
 
            FileOutputStream fos = openFileOutput(FILENAME,
                    Context.MODE_PRIVATE);
            fos.write(data.getBytes());
            fos.close();
 
        } catch (IOException e) {
            Log.e(TAG, "File write failed: " + e.toString());
        }
 
    }
 
    private void readFromFile() {
        File file = new File(this.getFilesDir() + "/", FILENAME);
        if (!file.exists()) {
            throw new RuntimeException("File not found");
        }
        Log.e("Testing", "Starting to read");
        BufferedReader reader = null;
        StringBuilder builder = null;
        try {
            reader = new BufferedReader(new FileReader(file));
            builder = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                builder.append(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        text.setText(builder.toString());
    }
 
}

Activity_main.xml

<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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >
 
    <Button
        android:id="@+id/writefile"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:layout_marginTop="35dp"
        android:text="Write" />
 
    <Button
        android:id="@+id/read"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/writefile"
        android:layout_alignParentRight="true"
        android:layout_centerVertical="true"
        android:text="Read" />
 
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/read"
        android:layout_alignParentBottom="true"
        android:layout_alignParentRight="true"
        android:layout_below="@+id/read"
        android:layout_marginTop="58dp"
        android:text="Output Text"
        android:textAppearance="?android:attr/textAppearanceLarge" />
 
</RelativeLayout>

readwritefile

Sanfoundry Global Education & Learning Series – 100+ Java Android Tutorials.

advertisement
advertisement
If you wish to look at all Tutorials, go to Java Android Tutorials.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.