Android Read Write Internal Storage File Example

Android data can be saved in internal storage ( ROM ) , external storage(SD card), shared preferences or SQLite database. This article will introduce how to read and write data in internal storage via java file.

1. Android Read Write Data To Internal File.

Android is based on Linux, android file system is Linux based also. Android studio provide android device monitor tool for you to monitor and transfer files between android device and your PC.

Please refer Android Device Monitor Cannot Open Data Folder Resolve Method.

1.1 Where Your Android App Internal Data File Saved In?

All android app internal data files is saved in /data/data/<your app package name> folder like below. In this example, my app data internal file is saved in /data/data/com.dev2qa.example folder.

android app internal file saved directory

From above picture, we can see that there are files and cache sub folder under the package name folder.

  1. files folder — android.content.Context’s  getFilesDir() method can return this folder. This folder is used to save general files.
  2. cache folder — android.content.Context’s  getCacheDir() method can return this folder. This folder is used to save cached files.
  3. When device internal storage space is low, cache files will be removed by android os automatically to make internal storage space bigger. Generally you need to delete the unused cache files in code timely, totally cache file size is better not more than 1 MB.

1.2 Read Write Android File Code Snippets.

Android application is written in java, so the file operation use java also. Below is the code snippets for read / write data from / to file in android.

1.2.1 Read Android File In files Folder.
  1. Call android.content.Context‘s openFileInput(userEmalFileName) method to get FileInputStream object.
  2. The input parameter is just the file name.
  3. This file should be saved in files folder.
  4. Then use the FileInputStream object to read data.
Context ctx = getApplicationContext();

FileInputStream fileInputStream = ctx.openFileInput(userEmalFileName);

InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);

BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

String lineData = bufferedReader.readLine();
1.2.2 Read Android File In cache Folder.
File file = new File(getCacheDir(), userEmalFileName);

FileInputStream fileInputStream = new FileInputStream(file);
1.2.3 Write File In files Folder.
Method 1 :

Use Context’s getFilesDir() to get files folder.

File file = new File(getFilesDir(), userEmalFileName);

FileOutputStream fileOutputStream = new FileOutputStream(file);

OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);

BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

bufferedWriter.write(data);
Method 2 :

Call Context’s openFileOutput(userEmalFileName, Context.MODE_APPEND); method to get FileOutputStream object.

The first parameter is the file name, the second parameter’s value can be:

  1. Context.MODE_PRIVATE : This means this file can only be read write by this android app which create it. This mode will overwrite exist file, if not exist then create it.
  2. Context.MODE_APPEND : This mode will append data to exist file. If not exist it will create a new one.
FileOutputStream fileOutputStream = ctx.openFileOutput(userEmalFileName, Context.MODE_PRIVATE);

1.2.4 Write File In cache Folder.

READ :   Android Device Monitor Cannot Open Data Folder Resolve Method

Use Context’s getCacheDir() to get cache folder.

File file = new File(getCacheDir(), userEmalFileName); 

FileOutputStream fileOutputStream = new FileOutputStream(file);

2. Android Internal File Operation Example.

android read write internal storage file example

After you run above example, you can see below files in android device monitor. You can pull down the file to your local PC to see the file content also.

If you meet any problem in using android device monitor, please refer Android Device Monitor Cannot Open Data Folder Resolve Method. This article will tell you how to resolve those error.

android read write internal storage file result

2.1 Layout Xml File.

activity_write_read_file.xml

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <EditText
        android:id="@+id/write_read_file_edit_text"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Input your email."/>

    <Button
        android:id="@+id/write_to_file_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Write To File"/>

    <Button
        android:id="@+id/read_from_file_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Read From File"/>

    <Button
        android:id="@+id/create_cached_file_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Create Cached File"/>

    <Button
        android:id="@+id/read_cached_file_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Read Cached File"/>

    <Button
        android:id="@+id/create_temp_file_button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Create Temp File"/>

</LinearLayout>

2.2 Activity Java File.

WriteReadFileActivity.java

package com.dev2qa.example.storage.file;

import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.dev2qa.example.R;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

public class WriteReadFileActivity extends AppCompatActivity {

    private String TAG_WRITE_READ_FILE = "TAG_WRITE_READ_FILE";

    private String userEmalFileName = "userEmail.txt";

    private String cacheFileName = "customCache.txt";

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

        setTitle("dev2qa.com - Android Read Write Internal Storage File Example.");

        final EditText editText = (EditText)findViewById(R.id.write_read_file_edit_text);

        // Write to internal file button.
        Button writeToFileButton = (Button)findViewById(R.id.write_to_file_button);
        writeToFileButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String userEmail = editText.getText().toString();

                if(TextUtils.isEmpty(userEmail))
                {
                    Toast.makeText(getApplicationContext(), "Input data can not be empty.", Toast.LENGTH_LONG).show();
                    return;
                }else {
                    Context ctx = getApplicationContext();

                    /*
                    This comments code can also write data to android internal file.
                    File file = new File(getFilesDir(), userEmalFileName);
                    writeDataToFile(file, userEmail);
                    */

                    try
                    {
                        FileOutputStream fileOutputStream = ctx.openFileOutput(userEmalFileName, Context.MODE_PRIVATE);
                        writeDataToFile(fileOutputStream, userEmail);
                    }catch(FileNotFoundException ex)
                    {
                        Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex);
                    }

                    Toast.makeText(ctx, "Data has been written to file " + userEmalFileName, Toast.LENGTH_LONG).show();
                }
            }
        });

        // Read from internal file.
        Button readFromFileButton = (Button)findViewById(R.id.read_from_file_button);
        readFromFileButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Context ctx = getApplicationContext();

                    FileInputStream fileInputStream = ctx.openFileInput(userEmalFileName);

                    String fileData = readFromFileInputStream(fileInputStream);

                    if(fileData.length()>0) {
                        editText.setText(fileData);
                        editText.setSelection(fileData.length());
                        Toast.makeText(ctx, "Load saved data complete.", Toast.LENGTH_SHORT).show();
                    }else
                    {
                        Toast.makeText(ctx, "Not load any data.", Toast.LENGTH_SHORT).show();
                    }
                }catch(FileNotFoundException ex)
                {
                    Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex);
                }
            }
        });

        // Write to internal cache file button.
        Button createCachedFileButton = (Button)findViewById(R.id.create_cached_file_button);
        createCachedFileButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String userEmail = editText.getText().toString();
                if(TextUtils.isEmpty(userEmail))
                {
                    Toast.makeText(getApplicationContext(), "Input data can not be empty.", Toast.LENGTH_LONG).show();
                    return;
                }else {

                    File file = new File(getCacheDir(), cacheFileName);

                    writeDataToFile(file, userEmail);

                    Toast.makeText(getApplicationContext(), "Cached file is created in file " + cacheFileName, Toast.LENGTH_LONG).show();
                }
            }
        });

        // Read from cache file.
        Button readCacheFileButton = (Button)findViewById(R.id.read_cached_file_button);
        readCacheFileButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    Context ctx = getApplicationContext();

                    File cacheFileDir = new File(getCacheDir(), cacheFileName);

                    FileInputStream fileInputStream = new FileInputStream(cacheFileDir);

                    String fileData = readFromFileInputStream(fileInputStream);

                    if(fileData.length()>0) {
                        editText.setText(fileData);
                        editText.setSelection(fileData.length());
                        Toast.makeText(ctx, "Load saved cache data complete.", Toast.LENGTH_SHORT).show();
                    }else
                    {
                        Toast.makeText(ctx, "Not load any cache data.", Toast.LENGTH_SHORT).show();
                    }
                }catch(FileNotFoundException ex)
                {
                    Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex);
                }
            }
        });


        // Write to internal temp file button.
        Button createTempFileButton = (Button)findViewById(R.id.create_temp_file_button);
        createTempFileButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    String userEmail = editText.getText().toString();
                    if(TextUtils.isEmpty(userEmail))
                    {
                        Toast.makeText(getApplicationContext(), "Input data can not be empty.", Toast.LENGTH_LONG).show();
                        return;
                    }else {
                        // This method will create a temp file in android cache folder,
                        // temp file prefix is temp, suffix is .txt, each temp file name is unique.
                        File tempFile = File.createTempFile("temp", ".txt", getCacheDir());

                        String tempFileName = tempFile.getAbsolutePath();

                        writeDataToFile(tempFile, userEmail);

                        Toast.makeText(getApplicationContext(), "Temp file is created, file name is " + tempFileName, Toast.LENGTH_LONG).show();
                    }
                }catch(IOException ex)
                {
                    Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex);
                }
            }
        });

    }

    // This method will write data to file.
    private void writeDataToFile(File file, String data)
    {
        try {
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            this.writeDataToFile(fileOutputStream, data);
            fileOutputStream.close();
        }catch(FileNotFoundException ex)
        {
            Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex);
        }catch(IOException ex)
        {
            Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex);
        }
    }

    // This method will write data to FileOutputStream.
    private void writeDataToFile(FileOutputStream fileOutputStream, String data)
    {
        try {
            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
            BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);

            bufferedWriter.write(data);

            bufferedWriter.flush();
            bufferedWriter.close();
            outputStreamWriter.close();
        }catch(FileNotFoundException ex)
        {
            Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex);
        }catch(IOException ex)
        {
            Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex);
        }
    }

    // This method will read data from FileInputStream.
    private String readFromFileInputStream(FileInputStream fileInputStream)
    {
        StringBuffer retBuf = new StringBuffer();

        try {
            if (fileInputStream != null) {
                InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
                BufferedReader bufferedReader = new BufferedReader(inputStreamReader);

                String lineData = bufferedReader.readLine();
                while (lineData != null) {
                    retBuf.append(lineData);
                    lineData = bufferedReader.readLine();
                }
            }
        }catch(IOException ex)
        {
            Log.e(TAG_WRITE_READ_FILE, ex.getMessage(), ex);
        }finally
        {
            return retBuf.toString();
        }
    }
}

If you meet below error message when you run this example.

READ :   How To Download APK From Google Play Online

Instant Run requires ‘Tools | Android | Enable ADB integration’ to be enabled.

error instant run require enable adb integration

You can click Tools —> Android menu, and check Enable ADB integration option in popup menu to resolve it.

tools android enable adb integration

(Visited 7,671 times, 1 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.