Android External Storage Tutorial with Examples
1. Android External Storage
No ADS
Android External Storage: a place to store addition data of Android, the files that you store here is not applied the security system.
Usually there are two types of external storage:
- Fixed external storage: Commonly understood as the hard drive of the device.
- Removable storage: Such as SD Card.
Use the static method of Environment class you can get the information on the directory of the external storage.
Here is the results table when running on the emulator:
Method | Returns |
getDataDirectory() | /data |
getDownloadCacheDirectory() | /cache |
getExternalStorageState() | mounted |
getExternalStoragePublicDirectory(Environment.Music): | /storage/emulated/0/Music |
getDownloadCacheDirectory() | /cache |
getRootDirectory() | /system |
To read/write the data on the external storage requires you to configure AndroidManifest.xml, added:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
With Android Level> = 23 to read and write data on the in external storage device, you need to ask the user by using code. (See in the example).
Android API Level < 29
With Android API Level < 29, apps can store its data on external storage, specifically in the folder below (or subfolders).
if (android.os.Build.VERSION.SDK_INT < 29) {
// ==> /storage/emulated/0 (Emulator)
File dir = Environment.getExternalStorageDirectory();
}
The storage method mentioned above can cause conflicts between different applications, since all of these applications can store its data in the same directory (or subfolders), further if you uninstall an application, the data created by it still exists on the external storage.
Android API Level 29+
With Android API 29+, each application stores its created data in a different folder on the external storage. When users uninstall application all data created by it will also be deleted.
if (android.os.Build.VERSION.SDK_INT >= 29) {
// ==> /storage/emulated/0/Android/data/org.o7planning.externalstoragedemo/files
File dir = this.getExternalFilesDir(null);
}
This class may be useful to you when working with external storage:
ExternalStorageUtils
package org.o7planning.externalstoragedemo.utils;
import android.content.Context;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import androidx.annotation.RequiresApi;
import java.io.File;
public class ExternalStorageUtils {
// Check whether the external storage is mounted or not.
public static boolean isExternalStorageMounted() {
String dirState = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED.equals(dirState))
{
return true;
}else
{
return false;
}
}
// Check whether the external storage is read only or not.
public static boolean isExternalStorageReadOnly() {
String dirState = Environment.getExternalStorageState();
if(Environment.MEDIA_MOUNTED_READ_ONLY.equals(dirState))
{
return true;
}else
{
return false;
}
}
// Get private external storage base directory.
public static String getPrivateExternalStorageBaseDir(Context context, String dirType)
{
String ret = "";
if(isExternalStorageMounted()) {
File file = context.getExternalFilesDir(dirType);
ret = file.getAbsolutePath();
}
return ret;
}
// Get private cache external storage base directory.
public static String getPrivateCacheExternalStorageBaseDir(Context context)
{
String ret = "";
if(isExternalStorageMounted()) {
File file = context.getExternalCacheDir();
ret = file.getAbsolutePath();
}
return ret;
}
// Get public external storage base directory.
public static String getPublicExternalStorageBaseDir()
{
String ret = "";
if(isExternalStorageMounted()) {
File file = Environment.getExternalStorageDirectory();
ret = file.getAbsolutePath();
}
return ret;
}
// Get public external storage base directory.
public static String getPublicExternalStorageBaseDir(String dirType)
{
String ret = "";
if(isExternalStorageMounted()) {
File file = Environment.getExternalStoragePublicDirectory(dirType);
ret = file.getAbsolutePath();
}
return ret;
}
// Get external storage disk space, return MB
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public static long getExternalStorageSpace() {
long ret = 0;
if (isExternalStorageMounted()) {
StatFs fileState = new StatFs(getPublicExternalStorageBaseDir());
// Get total block count.
long count = fileState.getBlockCountLong();
// Get each block size.
long size = fileState.getBlockSizeLong();
// Calculate total space size
ret = count * size / 1024 / 1024;
}
return ret;
}
// Get external storage left free disk space, return MB
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public static long getExternalStorageLeftSpace() {
long ret = 0;
if (isExternalStorageMounted()) {
StatFs fileState = new StatFs(getPublicExternalStorageBaseDir());
// Get free block count.
long count = fileState.getFreeBlocksLong();
// Get each block size.
long size = fileState.getBlockSizeLong();
// Calculate free space size
ret = count * size / 1024 / 1024;
}
return ret;
}
// Get external storage available disk space, return MB
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
public static long getExternalStorageAvailableSpace() {
long ret = 0;
if (isExternalStorageMounted()) {
StatFs fileState = new StatFs(getPublicExternalStorageBaseDir());
// Get available block count.
long count = fileState.getAvailableBlocksLong();
// Get each block size.
long size = fileState.getBlockSizeLong();
// Calculate available space size
ret = count * size / 1024 / 1024;
}
return ret;
}
}
2. Read and write files on the external storage example
No ADS
Create a project named ExternalStorageDemo.
- File > New > New Project > Empty Activity
- Name: ExternalStorageDemo
- Package name: org.o7planning.externalstoragedemo
- Language: Java
AndroidManifest.xml configuration allows read and write data on the external storage memory.
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Full content of AndroidManifest.xml:
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="org.o7planning.externalstoragedemo">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
The application interface:
If you are interested in the interface design steps of this application, please see the appendix at the end of the article.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="48dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="19dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:ems="10"
android:inputType="textPersonName"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<LinearLayout
android:id="@+id/linearLayout"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:orientation="horizontal"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/editText">
<Button
android:id="@+id/button_save"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Save" />
<Button
android:id="@+id/button_read"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="Read" />
<Button
android:id="@+id/button_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="0"
android:text="List Dirs" />
</LinearLayout>
<TextView
android:id="@+id/textView"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_marginStart="16dp"
android:layout_marginLeft="16dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="16dp"
android:layout_marginRight="16dp"
android:layout_marginBottom="16dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/linearLayout" />
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
package org.o7planning.externalstoragedemo;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
public class MainActivity extends AppCompatActivity {
private EditText editText;
private TextView textView;
private Button saveButton;
private Button readButton;
private Button listButton;
private static final String LOG_TAG = "ExternalStorageDemo";
private static final int REQUEST_ID_READ_PERMISSION = 100;
private static final int REQUEST_ID_WRITE_PERMISSION = 200;
private final String fileName = "note.txt";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
saveButton = (Button) findViewById(R.id.button_save);
readButton = (Button) findViewById(R.id.button_read);
listButton = (Button) findViewById(R.id.button_list);
saveButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
askPermissionAndWriteFile();
}
});
readButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
askPermissionAndReadFile();
}
});
listButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
listExternalStorages();
}
});
}
private void askPermissionAndWriteFile() {
boolean canWrite = this.askPermission(REQUEST_ID_WRITE_PERMISSION,
Manifest.permission.WRITE_EXTERNAL_STORAGE);
if(!canWrite) {
Toast.makeText(getApplicationContext(),
"You do not allow this app to write files.", Toast.LENGTH_LONG).show();
return;
}
//
this.writeFile();
}
private void askPermissionAndReadFile() {
boolean canRead = this.askPermission(REQUEST_ID_READ_PERMISSION,
Manifest.permission.READ_EXTERNAL_STORAGE);
//
if (!canRead) {
Toast.makeText(getApplicationContext(),
"You do not allow this app to read files.", Toast.LENGTH_LONG).show();
return;
}
//
this.readFile();
}
// With Android Level >= 23, you have to ask the user
// for permission with device (For example read/write data on the device).
private boolean askPermission(int requestId, String permissionName) {
Log.i(LOG_TAG, "Ask for Permission: " + permissionName);
Log.i(LOG_TAG, "Build.VERSION.SDK_INT: " + android.os.Build.VERSION.SDK_INT);
if (android.os.Build.VERSION.SDK_INT >= 23) {
// Check if we have permission
int permission = ActivityCompat.checkSelfPermission(this, permissionName);
Log.i(LOG_TAG, "permission: " + permission);
Log.i(LOG_TAG, "PackageManager.PERMISSION_GRANTED: " + PackageManager.PERMISSION_GRANTED);
if (permission != PackageManager.PERMISSION_GRANTED) {
// If don't have permission so prompt the user.
this.requestPermissions(
new String[]{permissionName},
requestId
);
return false;
}
}
return true;
}
// As soon as the user decides, allows or doesn't allow.
@Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
//
// Note: If request is cancelled, the result arrays are empty.
if (grantResults.length > 0) {
switch (requestCode) {
case REQUEST_ID_READ_PERMISSION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
readFile();
}
}
case REQUEST_ID_WRITE_PERMISSION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
writeFile();
}
}
}
} else {
Toast.makeText(getApplicationContext(), "Permission Cancelled!", Toast.LENGTH_SHORT).show();
}
}
// IMPORTANT!!
public File getAppExternalFilesDir() {
if (android.os.Build.VERSION.SDK_INT >= 29) {
// /storage/emulated/0/Android/data/org.o7planning.externalstoragedemo/files
return this.getExternalFilesDir(null);
} else {
// @Deprecated in API 29.
// /storage/emulated/0
return Environment.getExternalStorageDirectory();
}
}
private void writeFile() {
try {
File extStore = this.getAppExternalFilesDir( );
boolean canWrite = extStore.canWrite();
Log.i(LOG_TAG, "Can write: " + extStore.getAbsolutePath()+" : " + canWrite);
// ==> /storage/emulated/0/note.txt (API < 29)
// ==> /storage/emulated/0/Android/data/org.o7planning.externalstoragedemo/files/note.txt (API >=29)
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i(LOG_TAG, "Save to: " + path);
String data = editText.getText().toString();
Log.i(LOG_TAG, "Data: " + data);
File myFile = new File(path);
FileOutputStream fOut = new FileOutputStream(myFile);
fOut.write(data.getBytes("UTF-8"));
fOut.close();
Toast.makeText(getApplicationContext(), fileName + " saved", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Write Error:" + e.getMessage(), Toast.LENGTH_LONG).show();
Log.e(LOG_TAG, "Write Error: " + e.getMessage());
e.printStackTrace();
}
}
private void readFile() {
File extStore = this.getAppExternalFilesDir();
// ==> /storage/emulated/0/note.txt (API < 29)
// ==> /storage/emulated/0/Android/data/org.o7planning.externalstoragedemo/note.txt (API >=29)
String path = extStore.getAbsolutePath() + "/" + fileName;
Log.i(LOG_TAG, "Read file: " + path);
String s = "";
String fileContent = "";
try {
File myFile = new File(path);
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
while ((s = myReader.readLine()) != null) {
fileContent += s + "\n";
}
myReader.close();
this.textView.setText(fileContent);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Read Error:" + e.getMessage(), Toast.LENGTH_LONG).show();
Log.e(LOG_TAG, "Read Error: " + e.getMessage());
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), fileContent, Toast.LENGTH_LONG).show();
}
private void listExternalStorages() {
StringBuilder sb = new StringBuilder();
sb.append("Data Directory: ").append("\n - ")
.append(Environment.getDataDirectory().toString()).append("\n");
sb.append("Download Cache Directory: ").append("\n - ")
.append(Environment.getDownloadCacheDirectory().toString()).append("\n");
sb.append("External Storage State: ").append("\n - ")
.append(Environment.getExternalStorageState().toString()).append("\n");
sb.append("External Storage Directory: ").append("\n - ")
.append(Environment.getExternalStorageDirectory().toString()).append("\n");
sb.append("Is External Storage Emulated?: ").append("\n - ")
.append(Environment.isExternalStorageEmulated()).append("\n");
sb.append("Is External Storage Removable?: ").append("\n - ")
.append(Environment.isExternalStorageRemovable()).append("\n");
sb.append("External Storage Public Directory (Music): ").append("\n - ")
.append(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).toString()).append("\n");
sb.append("Download Cache Directory: ").append("\n - ")
.append(Environment.getDownloadCacheDirectory().toString()).append("\n");
sb.append("Root Directory: ").append("\n - ")
.append(Environment.getRootDirectory().toString()).append("\n");
Log.i(LOG_TAG, sb.toString());
this.textView.setText(sb.toString());
}
}
The app will save a file to the SD Card of the Emulator, so make sure you have your SD Card set up.
Running app:
See more about "Device File Explorer".
No ADS
Android Programming Tutorials
- Format Credit Card Number with Android TextWatcher
- Android Networking Tutorial with Examples
- Android TextInputLayout Tutorial with Examples
- Create a simple File Finder Dialog in Android
- Android AutoCompleteTextView and MultiAutoCompleteTextView Tutorial with Examples
- Using image assets and icon assets of Android Studio
- Android AsyncTaskLoader Tutorial with Examples
- Android ImageSwitcher Tutorial with Examples
- Android TimePickerDialog Tutorial with Examples
- Android FrameLayout Tutorial with Examples
- Android TimePicker Tutorial with Examples
- How to disable the permissions already granted to the Android application?
- Android ContextMenu Tutorial with Examples
- Android Camera Tutorial with Examples
- Get Phone Number in Android using TelephonyManager
- Android Clipboard Tutorial with Examples
- Android DatePickerDialog Tutorial with Examples
- Android SMS Tutorial with Examples
- Android Space Tutorial with Examples
- Android ScrollView and HorizontalScrollView Tutorial with Examples
- Install Android Studio on Windows
- Android VideoView Tutorial with Examples
- Android ProgressBar Tutorial with Examples
- Android External Storage Tutorial with Examples
- Android 2D Game Tutorial for Beginners
- Enable USB Debugging on Android Device
- Android MediaPlayer Tutorial with Examples
- Android Phone Call Tutorial with Examples
- Example of an explicit Android Intent, calling another Intent
- Android TextWatcher Tutorial with Examples
- Configure Android Emulator in Android Studio
- Android PopupMenu Tutorial with Examples
- Android CharacterPickerDialog Tutorial with Examples
- Android ListView with Checkbox using ArrayAdapter
- Android RadioGroup and RadioButton Tutorial with Examples
- Android AsyncTask Tutorial with Examples
- Android SnackBar Tutorial with Examples
- Android Spinner Tutorial with Examples
- Android ListView Tutorial with Examples
- Android TextView Tutorial with Examples
- Android SeekBar Tutorial with Examples
- Android JSON Parser Tutorial with Examples
- How to know the phone number of Android Emulator and change it
- Android LinearLayout Tutorial with Examples
- Android ViewPager2 Tutorial with Examples
- Android Text to Speech Tutorial with Examples
- Android RatingBar Tutorial with Examples
- Android DialogFragment Tutorial with Examples
- Android Wifi Scanning Tutorial with Examples
- Android Fragments Tutorial with Examples
- Create a simple File Chooser in Android
- Android DatePicker Tutorial with Examples
- Example of implicit Android Intent, open a URL, send an email
- Using Android Device File Explorer
- Android ToggleButton Tutorial with Examples
- Google Maps Android API Tutorial with Examples
- How to add external libraries to Android Project in Android Studio?
- Android EditText Tutorial with Examples
- Android ImageButton Tutorial with Examples
- Android Notifications Tutorial with Examples
- Android CheckBox Tutorial with Examples
- Android Services Tutorial with Examples
- Android Dialog Tutorial with Examples
- Android Tutorial for Beginners - Basic examples
- Create a custom Android Toast
- Android Intents Tutorial with Examples
- Android WebView Tutorial with Examples
- Android Chip and ChipGroup Tutorial with Examples
- Android GridView Tutorial with Examples
- Android Switch Tutorial with Examples
- How to remove applications from Android Emulator?
- Android QuickContactBadge Tutorial with Examples
- Android Chronometer Tutorial with Examples
- Android OptionMenu Tutorial with Examples
- Install Intel® HAXM for Android Studio
- Playing Sound effects in Android with SoundPool
- Android Internal Storage Tutorial with Examples
- Android AlertDialog Tutorial with Examples
- Android SharedPreferences Tutorial with Examples
- ChipGroup and Chip Entry Example
- Android SQLite Database Tutorial with Examples
- Android Toast Tutorial with Examples
- Android TableLayout Tutorial with Examples
- Android Button Tutorial with Examples
- Android FloatingActionButton Tutorial with Examples
- What is needed to get started with Android?
- Android UI Layouts Tutorial with Examples
- Android CardView Tutorial with Examples
- Setting SD Card for Android Emulator
- Android ImageView Tutorial with Examples
- Android Tutorial for Beginners - Hello Android
- Android StackView Tutorial with Examples
- Android TextClock Tutorial with Examples
Show More