Tutorial

Android External Storage - Read, Write, Save File

Published on August 3, 2022
Default avatar

By Anupam Chugh

Android External Storage - Read, Write, Save File

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Android external storage can be used to write and save data, read configuration files etc. This article is continuation of the Android Internal Storage tutorial in the series of tutorials on structured data storage in android.

Android External Storage

External storage such as SD card can also store application data, there’s no security enforced upon files you save to the external storage. In general there are two types of External Storage:

  • Primary External Storage: In built shared storage which is “accessible by the user by plugging in a USB cable and mounting it as a drive on a host computer”. Example: When we say Nexus 5 32 GB.
  • Secondary External Storage: Removable storage. Example: SD Card

All applications can read and write files placed on the external storage and the user can remove them. We need to check if the SD card is available and if we can write to it. Once we’ve checked that the external storage is available only then we can write to it else the save button would be disabled.

Android External Storage Example Project Structure

android external storage Firstly, we need to make sure that the application has permission to read and write data to the users SD card, so lets open up the AndroidManifest.xml and add the following permissions:

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

Also, external storage may be tied up by the user having mounted it as a USB storage device. So we need to check if the external storage is available and is not read only.

if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {  
   saveButton.setEnabled(false);
  }  

private static boolean isExternalStorageReadOnly() {  
  String extStorageState = Environment.getExternalStorageState();  
  if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {  
   return true;  
  }  
  return false;  
 }  
 
 private static boolean isExternalStorageAvailable() {  
  String extStorageState = Environment.getExternalStorageState();  
  if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {  
   return true;  
  }  
  return false;  
 }  

getExternalStorageState() is a static method of Environment to determine if external storage is presently available or not. As you can see if the condition is false we’ve disabled the save button.

Android External Storage Example Code

The activity_main.xml layout is defined as follows:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Reading and Writing to External Storage"
        android:textSize="24sp"/>

    <EditText android:id="@+id/myInputText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10" android:lines="5"
        android:minLines="3" android:gravity="top|left"
        android:inputType="textMultiLine">

        <requestFocus />
    </EditText>

    <LinearLayout
    android:layout_width="match_parent" android:layout_height="wrap_content"
    android:orientation="horizontal"
        android:weightSum="1.0"
        android:layout_marginTop="20dp">

    <Button android:id="@+id/saveExternalStorage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="SAVE"
        android:layout_weight="0.5"/>

    <Button android:id="@+id/getExternalStorage"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_weight="0.5"
        android:text="READ" />

    </LinearLayout>

    <TextView android:id="@+id/response"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:padding="5dp"
        android:text=""
        android:textAppearance="?android:attr/textAppearanceMedium" />

</LinearLayout>

Here apart from the save and read from external storage buttons we display the response of saving/reading to/from an external storage in a textview unlike in the previous tutorial where android toast was displayed. The MainActivity.java class is given below:

package com.journaldev.externalstorage;

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 android.os.Bundle;
import android.app.Activity;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;


public class MainActivity extends Activity {
    EditText inputText;
    TextView response;
    Button saveButton,readButton;

    private String filename = "SampleFile.txt";
    private String filepath = "MyFileStorage";
    File myExternalFile;
    String myData = "";

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

        inputText = (EditText) findViewById(R.id.myInputText);
        response = (TextView) findViewById(R.id.response);


         saveButton =
                (Button) findViewById(R.id.saveExternalStorage);
        saveButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    FileOutputStream fos = new FileOutputStream(myExternalFile);
                    fos.write(inputText.getText().toString().getBytes());
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                inputText.setText("");
                response.setText("SampleFile.txt saved to External Storage...");
            }
        });

        readButton = (Button) findViewById(R.id.getExternalStorage);
        readButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                try {
                    FileInputStream fis = new FileInputStream(myExternalFile);
                    DataInputStream in = new DataInputStream(fis);
                    BufferedReader br =
                            new BufferedReader(new InputStreamReader(in));
                    String strLine;
                    while ((strLine = br.readLine()) != null) {
                        myData = myData + strLine;
                    }
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                inputText.setText(myData);
                response.setText("SampleFile.txt data retrieved from Internal Storage...");
            }
        });

        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
            saveButton.setEnabled(false);
        }
        else {
            myExternalFile = new File(getExternalFilesDir(filepath), filename);
        }


    }
    private static boolean isExternalStorageReadOnly() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
            return true;
        }
        return false;
    }

    private static boolean isExternalStorageAvailable() {
        String extStorageState = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(extStorageState)) {
            return true;
        }
        return false;
    }


}
  1. Environment.getExternalStorageState(): returns path to internal SD mount point like “/mnt/sdcard”
  2. getExternalFilesDir(): It returns the path to files folder inside Android/data/data/application_package/ on the SD card. It is used to store any required files for your app (like images downloaded from web or cache files). Once the app is uninstalled, any data stored in this folder is gone too.

Also if the external storage is not available we disable the save button using the if condition that was discussed earlier in this tutorial. Below is our application running in android emulator, where we are writing data to file and then reading it. android external storage example read write save file Note: Make sure your Android Emulator is configured such that it has a SD card as shown in the image dialog from AVD below. Go to Tools->Android->Android Virtual Device, edit configurations->Show Advance Settings. android external storage config, android save file to external storage This brings an end to this tutorial. We’ll discuss storage using Shared Preferences in the next tutorial. You can download the final Android External Storage Project from the below link.

Download Android External Storage Example Project

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Anupam Chugh

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
February 16, 2022

Hi, We have created a file on internal storage outside cache and written some data on it. We want to be able to edit the file AFTER the application is deleted and re installed. When ever we try to access that file, after re installing the app, we get permission denied error. Can we re access the file after re installing the app? How to do it? Appreciate your time and help on this. Regards, Shariq

- Shariq Husain

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    January 13, 2021

    Hey I want to make a folder in primary external storage like storage/my folder not in the app data. Can you please suggest me any way to do it.

    - Amandeep

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      January 13, 2021

      edit text and button when i write something in edit text and click on button of save ,then open external memory storage .ask to user where you want to save the file .i am trying this but can’t find please help me.

      - Tanzeem

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 27, 2020

        Dont Save pdf file Internal Storage Android studio sdk 30. My Code String myFilePath = Environment.getExternalStorageDirectory().getPath() + “/REQUISITION.pdf”; File file = new File(myFilePath); try { myPdfDocument.writeTo(new FileOutputStream(file)); Toast.makeText(Createidepdf.this, “PDF File Create”, Toast.LENGTH_LONG).show(); } catch (IOException e) { e.printStackTrace(); }

        - Numan

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 24, 2020

          Hi, I am using Android 8.1. I have connected a secondary storage. We creates database for secondary storage in /data/data/my-package_name/databases/external.db When I am checking manually from the emulator database is exists and inside the database content is also present. When I am checking whether database is present or not through below code snippet File database = new File(“/data/data/my-package_name/database/external.db”); boolean result = database.exists(); But the result is always false. 1) Path is proper. 2) Given WRITE_EXTERNAL_STORAGE and READ_EXTERNAL_STORAGE permission 3) Even tried by giving path permission in AndroidManifest file. 4) getAbsolutePath() return proper file path but database.getAbsolutePath().exists() is returning always false. If any one have idea please suggest me?

          - Shreeja

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            August 1, 2020

            java.io.FileNotFoundException: /document/primary:WhatsApp/Media/WhatsApp Documents/UploadContest.xlsx (No such file or directory)

            - Raj

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              June 14, 2020

              omg this is so coool1!!! exactly what i wanted!! compact code

              - a fan

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                February 28, 2020

                File is saved to Internal Storage not SD card bro!

                - Kimpu

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  January 1, 2020

                  If i connected pen drive to device then how could i get path in my app to store video file in pen drive also if i get path of pen drive then how to create folder or save file in pen drive. If you have solution then please tell me

                  - pooja

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    November 11, 2019

                    can i know where my file is saved.

                    - anjali

                      Try DigitalOcean for free

                      Click below to sign up and get $200 of credit to try our products over 60 days!

                      Sign up

                      Join the Tech Talk
                      Success! Thank you! Please check your email for further details.

                      Please complete your information!

                      Get our biweekly newsletter

                      Sign up for Infrastructure as a Newsletter.

                      Hollie's Hub for Good

                      Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

                      Become a contributor

                      Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                      Welcome to the developer cloud

                      DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

                      Learn more
                      DigitalOcean Cloud Control Panel