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.

  1. Android is based on Linux, the android file system is Linux-based also.
  2. 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?

  1. All android app internal data files are saved in the /data/data/<your app package name> folder.
  2. 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.
  3. From the youtube video, we can see that there are files and cache subfolders under the package name folder.
  4. files folder — android.content.Context’s  getFilesDir() method can return this folder. This folder is used to save general files.
  5. cache folder — android.content.Context’s  getCacheDir() method can return this folder. This folder is used to save cached files.
  6. 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 the source code timely, the total cache file size is better not more than 1 MB.

1.2 Read Write Android File Code Snippets.

  1. Android application is written in java, so the file operation uses java classes also.
  2. Below are the code snippets for read/write data from/to the file in android.
1.2.1 Read Android File In The Package 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 the 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 The Package cache Folder.
  1. The below source code will read the android files in the package cache folder.
    File file = new File(getCacheDir(), userEmalFileName);
    
    FileInputStream fileInputStream = new FileInputStream(file);
1.2.3 Write File To The Package files Folder.
  1. Method 1: Use Context’s getFilesDir() to get the package files folder, then write file into it.
    File file = new File(getFilesDir(), userEmalFileName);
    
    FileOutputStream fileOutputStream = new FileOutputStream(file);
    
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
    
    BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
    
    bufferedWriter.write(data);
  2. Method 2: Call Context’s openFileOutput(userEmalFileName, Context.MODE_APPEND) method to get FileOutputStream object.
  3. The first parameter is the file name, the second parameter’s value can be one of the below values.
  4. Context.MODE_PRIVATE: This means this file can only be read/write by this android app that creates it. This mode will overwrite an existing file, if not exist then create it.
  5. Context.MODE_APPEND: This mode will append data to an existing file. If not exist it will create a new one.
    FileOutputStream fileOutputStream = ctx.openFileOutput(userEmalFileName, Context.MODE_PRIVATE);
1.2.4 Write File To The Package cache Folder.
  1. 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.

  1. You can watch the example demo video on youtube https://youtu.be/HqbRR6TQVvY.
  2. There are one input text box and five buttons on the android example app main screen.
  3. The buttons’ function can be easily understood by the button’s label text.
  4. The button’s label text is WRITE TO FILEREAD FROM FILE, CREATE CACHED FILE, READ CACHED FILE, CREATE TEMP FILE from up to bottom.
  5. 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 contents also.
    com.dev2qa.example/cache/customCache.txt
    
    com.dev2qa.example/cache/temp175008654.txt
    
    com.dev2qa.example/files/userEmail.txt
  6. 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.

  1. 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.

  1. 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();
            }
        }
    }
  2. 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.

3. Question & Answer.

3.1 Can not write text file to android internal storage.

  1. My android app is very simple, I just want to write some text to a file and save the text file to the internal storage. I follow this article to write source code, but I can not find the text file in both the android physical device and the simulator. I can not read the file content out in java source code. Can you tell me why? Thanks a lot.
  2. Android 11 has announced a new policy when you want to manage storage. The internal storage root folder can not be used to store files unless you add the below permission in your AndroidManifest.xml file.
    <uses-permission android:name="android.permission.MANAGE_EXTERNAL_STORAGE" />

    And when you run the application, you can request this permission to the user with the below code.

    requestPermissions(new String[]{MANAGE_EXTERNAL_STORAGE}, 1);

    Then you can process user response in the onRequestPermissionsResult() method in the activity.

2 thoughts on “Android Read Write Internal Storage File Example”

  1. 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();
       }
    }

Leave a Comment

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.