Android External Storage – Read, Write, Save File

Filed Under: Android

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()) {  

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=""
    android:layout_width="fill_parent" android:layout_height="fill_parent"

    <TextView android:layout_width="fill_parent"
        android:text="Reading and Writing to External Storage"

    <EditText android:id="@+id/myInputText"
        android:ems="10" android:lines="5"
        android:minLines="3" android:gravity="top|left"

        <requestFocus />

    android:layout_width="match_parent" android:layout_height="wrap_content"

    <Button android:id="@+id/saveExternalStorage"

    <Button android:id="@+id/getExternalStorage"
        android:text="READ" />


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


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 class is given below:

package com.journaldev.externalstorage;

import android.os.Bundle;
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 = "";

    protected void onCreate(Bundle savedInstanceState) {

        inputText = (EditText) findViewById(;
        response = (TextView) findViewById(;

         saveButton =
                (Button) findViewById(;
        saveButton.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
                try {
                    FileOutputStream fos = new FileOutputStream(myExternalFile);
                } catch (IOException e) {
                response.setText("SampleFile.txt saved to External Storage...");

        readButton = (Button) findViewById(;
        readButton.setOnClickListener(new OnClickListener() {
            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;
                } catch (IOException e) {
                response.setText("SampleFile.txt data retrieved from Internal Storage...");

        if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
        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.


  1. Shariq Husain says:


    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.

  2. Amandeep says:

    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.

  3. Tanzeem says:

    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.

  4. Numan says:

    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) {

  5. Shreeja says:


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

  6. Raj says: /document/primary:WhatsApp/Media/WhatsApp Documents/UploadContest.xlsx (No such file or directory)

  7. a fan says:

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

  8. Kimpu says:

    File is saved to Internal Storage not SD card bro!

  9. pooja says:

    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

    1. Developer says:

      Yes i have a solution

  10. anjali says:

    can i know where my file is saved.

    1. darshan kacha says:

      check in logcat there show your file path

  11. Govind says:

    I want to save data in sqlite for saving android app data offline and sync the saved data when online. please help.

  12. NicolasNy says:

    Nice, but this example only use primary external storage. What about Secondary External Storage as you comment at the top of this post?

  13. says:

    please post mediaplayer example.

    String mediaPath = “/sdcard/Omnamashivaya.mp3″;
    Uri uriPath = Uri.parse(mediaPath);

    MediaPlayer player = new MediaPlayer();
    try {

    Toast.makeText(getApplicationContext(),”Start to play”,Toast.LENGTH_LONG).show();

    } catch (IOException e) {

    i got below exception

    W/MediaPlayer: Couldn’t open /sdcard/Omnamashivaya.mp3: No content provider: /sdcard/Omnamashivaya.mp3
    W/System.err: /sdcard/Omnamashivaya.mp3 (Permission denied)
    at Method)
    W/System.err: at
    W/System.err: at
    at com.randy.chennaitourism.MainActivity$override.onCreate(
    at com.randy.chennaitourism.MainActivity$override.access$dispatch(Unknown Source:74)
    at com.randy.chennaitourism.MainActivity.onCreate(Unknown Source:15)
    W/System.err: at Source:0)
    at android.os.Handler.dispatchMessage(
    at android.os.Looper.loop(

    1. Mubeen says:

      i will recommend you to use exo-player

  14. satendra singh says:

    Ok i got it, e.g. in SDCARD the path android/data/app_name/files/MyFileStorage exists and the folder is empty.

    Android SDK built for x86 path android/data/app_name/files/MyFileStorage/SampleFile.txt exists, but what is the difference? :/ And why is the file not on the sdcard? ?
    Pla reply

  15. silverlokk says:

    if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)) {
    return true;
    return false;

    can be rewritten as:

    return Environment.MEDIA_MOUNTED_READ_ONLY.equals(extStorageState)

    Similarly, any if () { return true; } return false; can be rewritten return ()

    1. silverlokk says:

      Darn, I was afraid the comment box would strip out the left-angle brackets:

      if (<boolean-expression>) {return true;} return false; can be rewritten return (<boolean-expression>);

      Also forgot to end the statement with a semi-colon, so just as well 馃檪

  16. bagher says:

    hi dears
    im really happy to see these useful tutorial which you put theme in your site
    they are really useful and of clear summary
    thx alot

  17. khushbu says:

    nice tutorial!!!
    Even I was unable to find file path. I just debugged the app & tried this myExternalFile.getAbsolutePath(); & yipeee I found the correct file path.

    For me path is /storage/emulated/0/Android/data/your package name/files/MyFileStorage/SampleFile.txt

  18. Farhan says:

    Hello, great tutorial but you only covered the primary external storage, what about the secondary one?

  19. pradana says:

    thanks for share this 馃榾

  20. TRINH TRINH says:

    hi you!

    How to export data saved in sqlite to txt file
    Thank you !

    1. venkittu says:

      I also have some doubt….

  21. Matthew Johnson says:

    It is irritating beyond belief that a popup for “FREE eBook” covers up part of the display without even showing a Close button/box. Rest assured I will never buy anything advertised on this web site because of htat.

  22. babu says:

    Layout and layout parameters are not connected to java file in the above code .

  23. hackerassh says:

    hii sir I want make app for English grammar can u tell how can I do it sorry for my poor English

  24. Ankur Bhoot says:

    hi anupam ,
    i need your help if possible.
    i have get image using json web services.
    now i need to download this when click download button and image an store in my mobile storage .
    how can i perform this task.

  25. Hugo says:

    Hey your tutorial is awesome and working but i cant find the file, the folder “MyFileStorage” is empty but it’s still working… Can you tell me where i can find the file?

    1. Hugo says:

      Ok i got it, e.g. in SDCARD the path android/data/app_name/files/MyFileStorage exists and the folder is empty.

      Android SDK built for x86 path android/data/app_name/files/MyFileStorage/SampleFile.txt exists, but what is the difference? :/ And why is the file not on the sdcard? 馃檪

  26. rudolf says:

    hi anupam,

    thank you for your clear explanation and coding
    -and you made me nervous, when i received the text toast:
    ” read from internal storage ” ( its a typo )
    ha: its still the external – i am happy.
    i like to buy you a drink!

    thank you

      1. Monish says:

        I am not able to find the file on my device.Can you tell me where is file saved in external storage on our device.

  27. Hanan says:

    Thank You!

Comments are closed.

Generic selectors
Exact matches only
Search in title
Search in content