Read, Write and Delete File in External Storage


Create new project in Android Studio with steps as below:




Open res\values\strings.xml file and add new string as below:

<resources>
    <string name="app_name">Learn Android with Real Apps</string>
    <string name="folder_name">Folder Name</string>
    <string name="file_name">File Name</string>
    <string name="content">Content</string>
    <string name="write_file">Write File</string>
    <string name="read_file">Read File</string>
    <string name="delete_file">Delete File</string>
    <string name="done">Done</string>
    <string name="unavailable">External Storage is Unavailable</string>
</resources>

Open AndroidManifest.xml file in manifest folder and add permissions as below:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="android.demo.learnandroidwithrealapps">

    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

    </application>

</manifest>

Open res\layout\activity_main.xml file and create layout as below:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ffffff"
    android:orientation="vertical"
    tools:ignore="HardcodedText">

    <EditText
        android:id="@+id/editTextFolderName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/folder_name"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/editTextFileName"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/file_name"
        android:inputType="textPersonName" />

    <EditText
        android:id="@+id/editTextContent"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:hint="@string/content"
        android:inputType="textMultiLine" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <Button
            android:id="@+id/buttonWriteFile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/write_file" />

        <Button
            android:id="@+id/buttonReadFile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/read_file" />

        <Button
            android:id="@+id/buttonDeleteFile"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/delete_file" />
    </LinearLayout>

</LinearLayout>




Add code to MainActivity.java file in android.demo.learnandroidwithrealapps package as below:

package android.demo.learnandroidwithrealapps;

import android.Manifest;
import android.content.pm.PackageManager;
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.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileReader;

public class MainActivity extends AppCompatActivity {

    private EditText editTextFileName, editTextFolderName, editTextContent;
    private Button buttonDeleteFile, buttonWriteFile, buttonReadFile;

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

    private void assignPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
        }
    }

    private void initView() {
        editTextFileName = findViewById(R.id.editTextFileName);
        editTextFolderName = findViewById(R.id.editTextFolderName);
        editTextContent = findViewById(R.id.editTextContent);
        buttonReadFile = findViewById(R.id.buttonReadFile);
        buttonReadFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buttonReadFile_onClick(view);
            }
        });
        buttonWriteFile = findViewById(R.id.buttonWriteFile);
        buttonWriteFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buttonWriteFile_onClick(view);
            }
        });
        buttonDeleteFile = findViewById(R.id.buttonDeleteFile);
        buttonDeleteFile.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                buttonDeleteFile_onClick(view);
            }
        });
    }

    private void buttonReadFile_onClick(View view) {
        try {
            if (checkExternalMedia()) {
                File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File(sdCard.getAbsolutePath() + File.separator + editTextFolderName.getText().toString() + File.separator);
                File file = new File(dir, editTextFileName.getText().toString());
                StringBuilder result = new StringBuilder();
                String line = "";
                BufferedReader bufferedReader = new BufferedReader(new FileReader(file));
                while ((line = bufferedReader.readLine()) != null) {
                    result.append(line);
                }
                editTextContent.setText(result.toString());
            } else {
                Toast.makeText(getApplicationContext(), getString(R.string.unavailable), Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void buttonWriteFile_onClick(View view) {
        try {
            if (checkExternalMedia()) {
                File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File(sdCard.getAbsolutePath() + File.separator + editTextFolderName.getText().toString() + File.separator);
                dir.mkdirs();
                File file = new File(dir, editTextFileName.getText().toString());
                FileOutputStream fileOutputStream = new FileOutputStream(file);
                fileOutputStream.write(editTextContent.getText().toString().getBytes());
                fileOutputStream.close();
                Toast.makeText(getApplicationContext(), getString(R.string.done), Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), getString(R.string.unavailable), Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private void buttonDeleteFile_onClick(View view) {
        try {
            if (checkExternalMedia()) {
                File sdCard = Environment.getExternalStorageDirectory();
                File dir = new File(sdCard.getAbsolutePath() + File.separator + editTextFolderName.getText().toString() + File.separator);
                File file = new File(dir, editTextFileName.getText().toString());
                if(file.exists()) {
                    file.delete();
                }
                Toast.makeText(getApplicationContext(), getString(R.string.done), Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(getApplicationContext(), getString(R.string.unavailable), Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
        }
    }

    private boolean checkExternalMedia() {
        boolean mExternalStorageAvailable = false;
        boolean mExternalStorageWriteable = false;
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            mExternalStorageAvailable = mExternalStorageWriteable = true;
        } else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
            mExternalStorageAvailable = true;
            mExternalStorageWriteable = false;
        } else {
            mExternalStorageAvailable = mExternalStorageWriteable = false;
        }
        return mExternalStorageAvailable && mExternalStorageWriteable;
    }

}