In this tutorial you will learn via examples how to create or delete files in the android ecosystem.

Example 1: Create, Read and Delete a File in External Storage

This example project will teach you the following concepts:

  1. How to create a file in the android external storage.
  2. How to read a file in the android external storage.
  3. How to delete a file from the sd card.
  4. How to implement runtime permissions in Java android.
  5. How to create a file in the background thread using AsyncTask.

Here is the demo screenshot:

Android External Storage Write, Read and Delete Example

Step 1: Create Project

The first step is to create a Android Project in Android Studio.

Step 2: Add Dependencies

No special or third party dependencies are needed for this project.

Step 3: Design Layouts

Design your layout as follows:

activity_main.xml

Add a TextView, button and edittext:

<?xml version="1.0" encoding="UTF-8"?>

<RelativeLayout
    tools:context="com.example.ankitkumar.asynctask.MainActivity"
    android:background="#F58F"
    android:layout_height="match_parent"
    android:layout_width="match_parent"
    android:id="@+id/activity_main"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android">

<LinearLayout
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:id="@+id/ll_for_enter_data"
    android:weightSum="3"
    android:orientation="horizontal">

    <EditText
        android:background="#ffffF1"
        android:layout_height="75dp"
        android:layout_width="0dp"
        android:id="@+id/ed_enter_data"
        android:layout_weight="2.25"/>

    <Button
        android:layout_height="75dp"
        android:layout_width="0dp"
        android:id="@+id/button_add"
        android:layout_weight="0.75"
        android:text="Add Data"/>

</LinearLayout>

<TextView
    android:layout_height="wrap_content"
    android:layout_width="wrap_content"
    android:id="@+id/tv_title"
    android:text="Content from file"
    android:textColor="#eae8c2"
    android:layout_centerHorizontal="true"
    android:layout_marginTop="10dp"
    android:layout_below="@+id/ll_for_enter_data"
    android:textSize="18sp"/>

<TextView
    android:background="#303F9F"
    android:layout_height="100dp"
    android:layout_width="match_parent"
    android:id="@+id/tv_show_data"
    android:text="Data from file"
    android:textColor="#000000"
    android:layout_marginTop="10dp"
    android:layout_below="@+id/tv_title"
    android:textSize="16sp"/>

<Button
    android:layout_height="wrap_content"
    android:layout_width="match_parent"
    android:id="@+id/button_delete"
    android:text="Delete File"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"/>

</RelativeLayout>

Step : Write Code

Go to your MainActivity.java and add imports including the following:

       import android.Manifest;
        import android.content.Intent;
        import android.content.pm.PackageManager;
        import android.os.AsyncTask;
        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 java.io.BufferedReader;
        import java.io.DataInputStream;
        import java.io.File;
        import java.io.FileInputStream;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.io.InputStreamReader;
        import java.io.OutputStreamWriter;

Extend the AppCompatActivity and implement the View.OnClickListener:

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

Define the following constants:

    static final Integer LOCATION = 0x1;
    static final Integer CALL = 0x2;
    static final Integer WRITE_EXST = 0x3;
    static final Integer READ_EXST = 0x4;
    static final Integer CAMERA = 0x5;
    static final Integer ACCOUNTS = 0x6;
    static final Integer GPS_SETTINGS = 0x7;
    String myData = "";

Instantiate a File and pass the path of the file creation as below:

    final File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/TestFile.txt");

Define our views:

    Button buttonAdd, buttonDelete;
    EditText editTextForSave;
    TextView textViewForShowData;

Override our onCreate():

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

        editTextForSave = (EditText) findViewById(R.id.ed_enter_data);
        textViewForShowData = (TextView) findViewById(R.id.tv_show_data);

        buttonAdd = (Button) findViewById(R.id.button_add);
        buttonDelete = (Button) findViewById(R.id.button_delete);
        buttonAdd.setOnClickListener(this);
        buttonDelete.setOnClickListener(this);
    }

Here is how we create a method that will ask for permission at runtime:

    private void askForPermission(String permission, Integer requestCode) {
        if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
                //This is called if user has denied the permission before
                //In this case I am just asking the permission again
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
            }
        } else {
            //Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
        }
    }

Here is how invoke that method:

    public void ask(View v){
        switch (v.getId()){

            case R.id.button_add:
                askForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,WRITE_EXST);
                new MyAsynTask().execute();

                break;
            case R.id.button_delete:
                askForPermission(Manifest.permission.READ_EXTERNAL_STORAGE,READ_EXST);
                deleteFile();
                break;

            default:
                break;
        }
    }

And here is how we handle the permission result using the onRequestPermissionsResult():

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED){
            switch (requestCode) {

                case 3:
                    writeFile();
                    break;
                //Read External Storage
                case 4:
                    Intent imageIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(imageIntent, 11);
                    break;
            }

            Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
        }
    }

Here is how we write to a file on the SD card using the OutputStreamWriter:

    public void writeFile(){
        // write on SD card file data in the text box
        try {
            // buttonAdd.setEnabled(false);

            FileOutputStream fOut = new FileOutputStream(myFile);
            final OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
            String temp=editTextForSave.getText().toString();

            myOutWriter.append(temp);
            myOutWriter.append("\n");

            myOutWriter.close();
            fOut.close();
            Log.e("MA : ","Done writing SD");

        } catch (Exception e) {
            Log.e("catch : ",e.getMessage());
        }
//        editTextForSave.setText("");
        // buttonAdd.setEnabled(true);
    }

Here is how we read a file in the external storage using the BufferedReader:

    public void showData(){
        try {
            FileInputStream fis = new FileInputStream(myFile);
            DataInputStream in = new DataInputStream(fis);
            BufferedReader br =  new BufferedReader(new InputStreamReader(in));
            String strLine;
            while ((strLine = br.readLine()) != null) {
                myData = myData + "\n" + strLine;
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        textViewForShowData.setText(myData);
    }

Here is we delete a file from the SD card programmatically in android:

    public void deleteFile(){
        myFile.delete();
        myData = "";
        textViewForShowData.setText("File no Longer Exist.");
        Log.e("MA : ","File Deleted");
    }

Here is how we implement the asyncTask to write and read our data in the external storage:

    // The definition of our task class
    private class MyAsynTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            writeFile();
            showData();
            return "All Done!";
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            buttonAdd.setEnabled(false);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            textViewForShowData.setText(myData);
            editTextForSave.setText("");
            buttonAdd.setEnabled(true);
        }
    }
}

Here is the full code for the MainActivity:

MainActivity.java

package com.example.ankitkumar.asynctask;

import android.Manifest;
        import android.content.Intent;
        import android.content.pm.PackageManager;
        import android.os.AsyncTask;
        import android.os.Bundle;
        import android.os.Environment;
        import android.support.v4.app.ActivityCompat;
        import android.support.v4.content.ContextCompat;
        import android.support.v7.app.AppCompatActivity;
        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 java.io.BufferedReader;
        import java.io.DataInputStream;
        import java.io.File;
        import java.io.FileInputStream;
        import java.io.FileOutputStream;
        import java.io.IOException;
        import java.io.InputStreamReader;
        import java.io.OutputStreamWriter;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    static final Integer LOCATION = 0x1;
    static final Integer CALL = 0x2;
    static final Integer WRITE_EXST = 0x3;
    static final Integer READ_EXST = 0x4;
    static final Integer CAMERA = 0x5;
    static final Integer ACCOUNTS = 0x6;
    static final Integer GPS_SETTINGS = 0x7;
    String myData = "";

    final File myFile = new File(Environment.getExternalStorageDirectory().getAbsolutePath()+"/TestFile.txt");

    Button buttonAdd, buttonDelete;
    EditText editTextForSave;
    TextView textViewForShowData;

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

        editTextForSave = (EditText) findViewById(R.id.ed_enter_data);
        textViewForShowData = (TextView) findViewById(R.id.tv_show_data);

        buttonAdd = (Button) findViewById(R.id.button_add);
        buttonDelete = (Button) findViewById(R.id.button_delete);
        buttonAdd.setOnClickListener(this);
        buttonDelete.setOnClickListener(this);
    }

    private void askForPermission(String permission, Integer requestCode) {
        if (ContextCompat.checkSelfPermission(MainActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
            // Should we show an explanation?
            if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, permission)) {
                //This is called if user has denied the permission before
                //In this case I am just asking the permission again
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
            } else {
                ActivityCompat.requestPermissions(MainActivity.this, new String[]{permission}, requestCode);
            }
        } else {
            //Toast.makeText(this, "" + permission + " is already granted.", Toast.LENGTH_SHORT).show();
        }
    }

    public void ask(View v){
        switch (v.getId()){

            case R.id.button_add:
                askForPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE,WRITE_EXST);
                new MyAsynTask().execute();

                break;
            case R.id.button_delete:
                askForPermission(Manifest.permission.READ_EXTERNAL_STORAGE,READ_EXST);
                deleteFile();
                break;

            default:
                break;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(ActivityCompat.checkSelfPermission(this, permissions[0]) == PackageManager.PERMISSION_GRANTED){
            switch (requestCode) {

                case 3:
                    writeFile();
                    break;
                //Read External Storage
                case 4:
                    Intent imageIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                    startActivityForResult(imageIntent, 11);
                    break;
            }

            Toast.makeText(this, "Permission granted", Toast.LENGTH_SHORT).show();
        }else{
            Toast.makeText(this, "Permission denied", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onClick(View v) {
        ask(v);
    }

    public void writeFile(){
        // write on SD card file data in the text box
        try {
            // buttonAdd.setEnabled(false);

            FileOutputStream fOut = new FileOutputStream(myFile);
            final OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
            String temp=editTextForSave.getText().toString();

            myOutWriter.append(temp);
            myOutWriter.append("\n");

            myOutWriter.close();
            fOut.close();
            Log.e("MA : ","Done writing SD");

        } catch (Exception e) {
            Log.e("catch : ",e.getMessage());
        }
//        editTextForSave.setText("");
        // buttonAdd.setEnabled(true);
    }

    public void showData(){
        try {
            FileInputStream fis = new FileInputStream(myFile);
            DataInputStream in = new DataInputStream(fis);
            BufferedReader br =  new BufferedReader(new InputStreamReader(in));
            String strLine;
            while ((strLine = br.readLine()) != null) {
                myData = myData + "\n" + strLine;
            }
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
//        textViewForShowData.setText(myData);
    }

    public void deleteFile(){
        myFile.delete();
        myData = "";
        textViewForShowData.setText("File no Longer Exist.");
        Log.e("MA : ","File Deleted");
    }

    // The definition of our task class
    private class MyAsynTask extends AsyncTask<String, Integer, String> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            writeFile();
            showData();
            return "All Done!";
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            buttonAdd.setEnabled(false);
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            textViewForShowData.setText(myData);
            editTextForSave.setText("");
            buttonAdd.setEnabled(true);
        }
    }
}

Run

Copy the code into your project or download the code in the reference links below.

Reference

Find the reference links below:

Number Link
1. Download code
2. Follow code author