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 a java file.

1. Android Read Write Data To Internal File.

Android is based on Linux, the android file system is Linux-based also. Android studio provides the android device monitor tool for you to monitor and transfer files between Android devices 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 are saved in /data/data/<your app package name> folder. In this example, my app data internal file is saved in /data/data/com.dev2qa.example folder. You can watch the youtube video https://youtu.be/AJBgBBMKO5w to see the android app’s internal data files saved directory.

From the youtube video, we can see that there are files and cache subfolders 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 the device’s 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 source code timely, the total 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 uses java classes also. Below are 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 that creates it. This mode will overwrite existing file, if not exist then create it.
  2. Context.MODE_APPEND : This mode will append data to existing 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.

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.

You can watch the example demo video on youtube https://youtu.be/HqbRR6TQVvY. There are one input text box and five buttons on the android example app main screen. The buttons function can be easily understood by the button’s label text. The button’s label text is WRITE TO FILEREAD FROM FILE, CREATE CACHED FILE, READ CACHED FILE, CREATE TEMP FILE from up to bottom.

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

com.dev2qa.example/cache/customCache.txt

com.dev2qa.example/cache/temp175008654.txt

com.dev2qa.example/files/userEmail.txt

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

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 the error message Instant Run requires ‘Tools | Android | Enable ADB integration’ to be enabled when you run this example. You can click Tools —> Android menu, and check Enable ADB integration option in the popup menu to resolve it.

0 0 votes
Article Rating
Subscribe
Notify of
guest

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

2 Comments
Newest
Oldest Most Voted
Inline Feedbacks
View all comments
Muhammad Bilal Mohib-ul-Nabi

Thanks.Great Article Guys.

James
James

I am a beginner of android programming, and I want to write some data to a file saved in android internal storage device. I found this article and write the source code as below. But I found after I write the data to internal storage file with the method writeToFile, I can not read the written file content in android internal storage device in the readFileButton method. Can you tell me what wrong in my source code? Thanks a lot.

public void writeToFile(String fileName, String fileContent){

  try {
     // Create a FileOutputStream object with the provided file name.
     FileOutputStream fos = openFileOutput(fileName , Context.MODE_PRIVATE);

     // Write the file content to the file.
     fos.write(fileContent.getBytes());

     // Close the file output stream to flush the data to the file.
     fos.close();
  } catch (Exception e) {
    e.printStackTrace();
  }
}

public void readFileButton(View v) {
   // Read the file text content.
   try {

       // Define the internal stored file name.
       String fileName = “test.txt”;

       // Create a FileInputStream object.
       FileInputStream fis =openFileInput(fileName);

       // Create a InputStreamReader object.
       InputStreamReader isr = new InputStreamReader(fis);

       // Define the char array.
       char[] ib= new char[1024];

       // Store read out file data.
       String fileData = “”;

       // Read 1024 character data from file.
       int charRead = isr.read(ib);

       // While not end of the file.
       while (charRead>0) {

           // Convert the char array to a string object.
           String readstring = String.copyValueOf(inputBuffer,0,charRead);

           // Add the read out file data.
           fileData +=readstring;

           // Read data from the file again.
           charRead = isr.read(ib);
       }

       // Close the FileInputStream object.
       fis.close();

       // Close the InputStreamReader object.
       isr.close();

       // Show a toast popup dialog.
       Toast.makeText(ctx, fileData, Toast.LENGTH_LONG).show();
   } catch (Exception e) {
       e.printStackTrace();
   }
}

2
0
Would love your thoughts, please comment.x
()
x