Android Internal And External Storage Complete Guide

 Last Update:2025-06-23T00:00:00     .NET School AI Teacher - SELECT ANY TEXT TO EXPLANATION.    8 mins read      Difficulty-Level: beginner

Understanding the Core Concepts of Android Internal and External Storage

Android Internal and External Storage Explained in Detail

Internal Storage

Definition: Internal storage is the private space on an Android device allocated specifically for each app. Data stored here is only accessible by the app that created it and remains there as long as the app is installed. Once the app is uninstalled, its associated files on internal storage are automatically deleted.

Key Points:

  1. Accessibility: The data in internal storage can only be accessed by the app that wrote it or by the system. It provides enhanced security and privacy.
  2. Lifetime: Files persist only as long as the application remains installed on the device.
  3. Location: Typically, this storage is part of the device’s main storage (such as the system partition), which means it's finite and should be used judiciously.
  4. Performance: Accessing internal storage is generally faster compared to external storage because it's directly integrated with the device's system and processes.
  5. Use Cases: Ideal for storing sensitive data, configuration files, and other critical application resources that need strict access control.
  6. File System: Utilizes the traditional Linux file system, where each app has its own sandboxed directory structure (e.g., files/, cache/, databases/).

Methods:

  • Context.getFilesDir() or Context.openFileOutput(): These methods allow you to create and write files to internal storage.
  • Context.getCacheDir(): Used for temporary files that do not need to persist between app sessions.

Example Code Snippet:

// Writing to internal storage
String filename = "myfile";
String string = "Hello world!";
FileOutputStream outputStream;

try {
    outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
    outputStream.write(string.getBytes());
    outputStream.close();
} catch (IOException e) {
    e.printStackTrace();
}

// Reading from internal storage
FileInputStream inputStream;
try {
    inputStream = openFileInput(filename);
    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
    StringBuilder stringBuilder = new StringBuilder();
    String text;
    
    while ((text = bufferedReader.readLine()) != null) {
        stringBuilder.append(text).append('\n');
    }
    inputStream.close();
    Log.d("TAG", stringBuilder.toString());
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

External Storage

Definition: External storage refers to the shared storage available to all apps on an Android device, typically found in SD cards or USB drives. However, starting with Android 4.4 (KitKat), direct access to the root of external storage by apps is restricted. Instead, apps can use specific public directories or request scoped storage permissions.

Key Points:

  1. Accessibility: Public files can be accessed by any app and visible to users via standard file managers.
  2. Lifetime: Files persist even after the app is uninstalled unless explicitly deleted by the user or another app with appropriate permissions.
  3. Location: Usually an SD card or a secondary storage area on the device.
  4. Performance: Can be slower due to I/O operations over removable media.
  5. Use Cases: Suitable for sharing files among multiple apps, caching large non-critical data, and user-generated content like images and videos.
  6. File System: Organized into public directories like Music, Pictures, Videos, etc.

Public vs. Private External Storage:

  • Public External Storage: Files stored in public directories are accessible by any app and visible to the user in file managers. Examples include /sdcard/Music/, /sdcard/Pictures/.
  • Private External Storage: Introduced in Android 4.4, allows apps to store files in directories within the app-specific folder (/Android/data/<package-name>/). These files are private to the app unless the app grants them permission.

Permissions:

  • Starting from Android 6.0 (API level 23), apps need explicit runtime permissions to read/write to the external storage.
  • For Android 10 (API level 29) and above, scoped storage changes require apps to adopt more granular permissions.
  • WRITE_EXTERNAL_STORAGE: Allows an app to write to the public external storage only up to API 28.
  • READ_EXTERNAL_STORAGE: Allows an app to read from the public external storage.

Methods:

  • Environment.getExternalStorageDirectory(): Retrieves the directory for primary shared/external storage.
  • Context.getExternalFilesDir(String type): Returns the directory for app-specific files in the external storage.
  • MediaStore API: Use MediaStore to interact with and manage media files within the user's media library.

Handling Scoped Storage: From Android 11 onwards, scoped storage is enforced by default, limiting access to certain parts of the external filesystem. Apps must adapt their storage models accordingly:

  • Use ACTION_OPEN_DOCUMENT intent to request user permission to access specific files/directories.
  • Leverage MediaStore API to handle multimedia content.
  • Store important data in private app-specific directories if direct access to external storage is necessary.

Example Code Snippet:

Online Code run

🔔 Note: Select your programming language to check or run code at

💻 Run Code Compiler

Step-by-Step Guide: How to Implement Android Internal and External Storage

Android Storage Overview

Android devices store data in different types of storage areas:

  1. Internal Storage: Private to an app, deleted when the app is uninstalled. Used for application-specific data.
  2. External Storage: Shared among all apps, not deleted when an app is uninstalled. Used for media files, documents, etc.

Step-by-Step Guide

1. Internal Storage

Writing to Internal Storage:

  1. Add Permission: No special permission is required to read/write to the app's internal storage.

  2. Create a File and Write Data:

import android.content.Context;
import java.io.FileOutputStream;
import java.io.IOException;

public void writeInternalStorage(Context context, String fileName, String data) {
    try {
        FileOutputStream fos = context.openFileOutput(fileName, context.MODE_PRIVATE);
        fos.write(data.getBytes());
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  1. Read from the File:
import android.content.Context;
import java.io.FileInputStream;
import java.io.IOException;

public String readInternalStorage(Context context, String fileName) {
    String content = "";
    try {
        FileInputStream fis = context.openFileInput(fileName);
        int contentLength = fis.available();
        byte[] buffer = new byte[contentLength];
        fis.read(buffer);
        content = new String(buffer);
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return content;
}

Full Example Code for Internal Storage:

MainActivity.java:

import android.os.Bundle;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
    private static final String FILE_NAME = "example.txt";

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

        writeInternalStorage(FILE_NAME, "Hello, Internal Storage!");
        TextView textView = findViewById(R.id.textView);
        textView.setText(readInternalStorage(FILE_NAME));
    }

    public void writeInternalStorage(String fileName, String data) {
        try {
            FileOutputStream fos = openFileOutput(fileName, MODE_PRIVATE);
            fos.write(data.getBytes());
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String readInternalStorage(String fileName) {
        String content = "";
        try {
            FileInputStream fis = openFileInput(fileName);
            int contentLength = fis.available();
            byte[] buffer = new byte[contentLength];
            fis.read(buffer);
            content = new String(buffer);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Hello World!"/>
</RelativeLayout>

2. External Storage

Writing to External Storage:

  1. Add Permission: You need to add permission in the AndroidManifest.xml.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

From Android 10 and above, you need to modify this slightly:

<application
    ...
    android:requestLegacyExternalStorage="true">
    ...
</application>
  1. Check Runtime Permission (For Android 6.0+):
import android.Manifest;
import android.content.pm.PackageManager;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

public boolean checkPermissions() {
    int permissionState1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    int permissionState2 = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
    return permissionState1 == PackageManager.PERMISSION_GRANTED && permissionState2 == PackageManager.PERMISSION_GRANTED;
}

public void requestPermissions() {
    ActivityCompat.requestPermissions(this,
            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
            1);
}
  1. Create a File and Write Data:
import android.os.Environment;
import java.io.FileOutputStream;
import java.io.IOException;

public void writeExternalStorage(String fileName, String data) {
    try {
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath();
        FileOutputStream fos = new FileOutputStream(path + "/" + fileName);
        fos.write(data.getBytes());
        fos.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  1. Read from the File:
import android.os.Environment;
import java.io.FileInputStream;
import java.io.IOException;

public String readExternalStorage(String fileName) {
    String content = "";
    try {
        String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath();
        FileInputStream fis = new FileInputStream(path + "/" + fileName);
        int contentLength = fis.available();
        byte[] buffer = new byte[contentLength];
        fis.read(buffer);
        content = new String(buffer);
        fis.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return content;
}

Full Example Code for External Storage:

MainActivity.java:

import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private static final String FILE_NAME = "example.txt";

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

        if (checkPermissions()) {
            writeExternalStorage(FILE_NAME, "Hello, External Storage!");
            TextView textView = findViewById(R.id.textView);
            textView.setText(readExternalStorage(FILE_NAME));
        } else {
            requestPermissions();
        }
    }

    public boolean checkPermissions() {
        int permissionState1 = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
        int permissionState2 = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE);
        return permissionState1 == PackageManager.PERMISSION_GRANTED && permissionState2 == PackageManager.PERMISSION_GRANTED;
    }

    public void requestPermissions() {
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE},
                1);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
                writeExternalStorage(FILE_NAME, "Hello, External Storage!");
                TextView textView = findViewById(R.id.textView);
                textView.setText(readExternalStorage(FILE_NAME));
            }
        }
    }

    public void writeExternalStorage(String fileName, String data) {
        try {
            String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath();
            FileOutputStream fos = new FileOutputStream(path + "/" + fileName);
            fos.write(data.getBytes());
            fos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String readExternalStorage(String fileName) {
        String content = "";
        try {
            String path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOCUMENTS).getAbsolutePath();
            FileInputStream fis = new FileInputStream(path + "/" + fileName);
            int contentLength = fis.available();
            byte[] buffer = new byte[contentLength];
            fis.read(buffer);
            content = new String(buffer);
            fis.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return content;
    }
}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Hello World!"/>
</RelativeLayout>

Summary

In this guide, you’ve learned how to:

  • Write to and read from internal storage without additional permissions.
  • Write to and read from external storage, including requesting permissions at runtime for Android 6.0 and above.

Top 10 Interview Questions & Answers on Android Internal and External Storage

1. What are the differences between internal and external storage on an Android device?

Answer:

  • Internal Storage: This is built into the device and cannot be removed by the user. It's primarily used for storing system files, app data, and user-specific data like contacts, settings, photos, and videos. Internal storage benefits from encryption and protection mechanisms, making it more secure than external storage.
  • External Storage: External storage comes in the form of SD cards (if supported) or USB drives that can be inserted and removed from the device. It’s often used for media like photos, music, and videos, and for transferring files between devices. However, external storage is inherently less secure as it's easily accessible and prone to physical damage.

2. Can apps access both types of storage on an Android device?

Answer: Yes, apps can access both internal and external storage. Apps have dedicated private directories within internal storage for their exclusive use, but they can also request permission to read/write files in shared external storage areas. On Android 11 (API level 30) and above, apps must comply with new scoped storage rules that limit access to specific locations within external storage.

3. How does Android handle internal storage encryption?

Answer: Android encrypts internal storage by default starting from Android 5.0 Lollipop (API level 21). Encryption ensures that even if someone physically removes the internal storage chip from the device, the data remains unreadable without the correct decryption key, which is typically tied to the device unlock pattern or password. Full-disk encryption provides this security, enhancing the overall privacy of the device.

4. What permissions do I need to access external storage in Android?

Answer: To access files within external storage, apps generally require the READ_EXTERNAL_STORAGE and/or WRITE_EXTERNAL_STORAGE permissions in their AndroidManifest.xml. However, with the introduction of scoped storage in Android 11, these permissions alone are not enough to access shared folders. Apps must also declare their intent to use storage in the manifest file to access specific media collections directly, like Music, Photos, etc., using a combination of permissions and access requests.

5. What changes did Android 11 bring to external storage access?

Answer: Android 11 introduced a more restrictive approach to handling external storage known as Scoped Storage. This change means that apps have limited access to other apps' files on the external storage. Instead, apps are given access only to their own private directory (App-specific directory) and some predefined directories such as Documents, Download, Videos, Pictures, etc. Apps need to declare in their manifest how they intend to use these directories.

6. How can I check if my Android device has external storage?

Answer: You can check if your Android device has external storage by navigating to the Files app under Settings. The presence of an SD card slot will usually indicate availability of external storage. You can also use the following Android code snippet to programmatically determine if external storage is available:

String state = Environment.getExternalStorageState();
boolean isExternalStorageReadWrite =
    Environment.MEDIA_MOUNTED.equals(state);

7. What is primary vs secondary external storage in Android?

Answer:

  • Primary External Storage: This is considered part of the device's built-in storage. It's mounted as /storage/emulated/0 and is accessible to Android OS and apps. It's formatted as FAT32 by default to ensure compatibility across different devices. This area doesn't require root permissions to write to.
  • Secondary External Storage: Typically refers to an SD card (or similar removable storage). It’s mounted as /storage/sdcard1 or something similar and may not be accessible unless the user explicitly grants access and the app requests it through appropriate permissions.

8. How do you store large files in Android (internal or external)?

Answer: For large files like videos, high-resolution photographs, large documents, or audio tracks, it’s best practice to store them in external storage due to size limitations of internal storage. Use the getExternalStoragePublicDirectory() method for accessing shared storage, but adhere to scoped storage guidelines in Android 11 and later. Alternatively, you can use the getExternalFilesDir() method for storing within app-specific directories, which allows you to manage file permissions more securely.

9. Can external storage be used as a system backup location?

Answer: While some users might attempt to copy system files to an SD card, Android itself doesn’t provide native support for system backup to external storage, primarily because internal storage includes system data that requires specific integrity checks and management to ensure system stability after restoration. Instead, Android devices offer cloud backup services that back up user data to their respective cloud services securely.

10. What are best practices for managing data storage on Android?

Answer: Best practices for managing data storage on Android include:

  • Use Appropriate Storage Type: Store user-generated content like images, videos, and documents in external storage. Store app configuration files and databases in internal storage.
  • Avoid Hardcoding Paths: Use Android methods like getContext().getFilesDir(), getExternalFilesDir(String type) or Environment.getExternalStoragePublicDirectory() to get paths.
  • Handle Permissions: Request runtime permissions where necessary and comply with scoped storage guidelines introduced in Android 11.
  • Clean Up Resources: Delete unused files to free up space. Implement a background cleaning mechanism to manage cache and media files efficiently.
  • Use MediaStore APIs: For media files, use MediaStore APIs instead of writing directly to the file system to comply with best practices and security guidelines.
  • Optimize File Access: Avoid performing file read/write operations on UI threads as they can lead to freezing. Use asynchronous tasks or coroutines to perform file operations smoothly.
  • Backup Data Regularly: Use Android Backup Service or implement your own backup solutions to safeguard important data against accidental deletions or hardware failures.

You May Like This Related .NET Topic

Login to post a comment.