Giới thiệu
Bài viết hướng dẫn đọc/ghi file trên bộ nhớ ngoài (External Storage/SD Card) trên Android, bao gồm kiểm tra trạng thái bộ nhớ, xin quyền runtime và thao tác file I/O.
⚠️ Thay đổi quan trọng theo phiên bản Android
- Android 10 (API 29) trở đi: Scoped Storage - App chỉ truy cập thư mục riêng (
getExternalFilesDir()) không cần quyền. Không thể truy cập thư mục gốc SD Card. - Android 11+ (API 30+): Chỉ được truy cập thư mục app-specific. Cần
MANAGE_EXTERNAL_STORAGEcho quyền rộng (khó duyệt Play Store). - Ví dụ này dùng
getExternalFilesDir()- cách an toàn, hoạt động mọi phiên bản.
Các bước thực hiện
Bước 1: Tạo dự án mới
Android Studio → File → New Project → Empty Activity.
Bước 2: Giao diện (res/layout/activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
xmlns:tools="https://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="12dp"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Đọc và Ghi bộ nhớ ngoài"
android:textSize="24sp"
android:textStyle="bold"
android:textAlignment="center" />
<EditText
android:id="@+id/myInputText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="30dp"
android:ems="10"
android:gravity="top|start"
android:lines="5"
android:minLines="3" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:orientation="horizontal"
android:weightSum="1.0">
<Button
android:id="@+id/saveExternalStorage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="LƯU" />
<Button
android:id="@+id/getExternalStorage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="ĐỌC" />
</LinearLayout>
<TextView
android:id="@+id/response"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:padding="5dp"
android:text=""
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
Bước 3: Logic (src/MainActivity.java)
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
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;
public class MainActivity extends AppCompatActivity {
EditText editText;
TextView textView;
Button saveButton, readButton;
File myExternalFile;
String myData = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editText = findViewById(R.id.myInputText);
textView = findViewById(R.id.response);
saveButton = findViewById(R.id.saveExternalStorage);
readButton = findViewById(R.id.getExternalStorage);
// Nút LƯU
saveButton.setOnClickListener(v -> {
try {
FileOutputStream fos = new FileOutputStream(myExternalFile);
fos.write(editText.getText().toString().getBytes());
fos.close();
editText.setText("");
textView.setText("SampleFile.txt đã lưu vào External Storage...");
} catch (IOException e) {
e.printStackTrace();
}
});
// Nút ĐỌC
readButton.setOnClickListener(v -> {
try {
FileInputStream fis = new FileInputStream(myExternalFile);
DataInputStream in = new DataInputStream(fis);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String strLine;
myData = "";
while ((strLine = br.readLine()) != null) {
myData += strLine;
}
in.close();
editText.setText(myData);
textView.setText("Dữ liệu SampleFile.txt đã đọc từ External Storage...");
} catch (IOException e) {
e.printStackTrace();
}
});
// Kiểm tra bộ nhớ và khởi tạo file
if (!isExternalStorageAvailable() || isExternalStorageReadOnly()) {
saveButton.setEnabled(false);
} else {
String fileName = "SampleFile.txt";
String filePath = "MyFolder";
// Thư mục riêng của app: /Android/data/package.name/files/MyFolder/
myExternalFile = new File(getExternalFilesDir(filePath), fileName);
}
}
private static boolean isExternalStorageReadOnly() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED_READ_ONLY.equals(state);
}
private static boolean isExternalStorageAvailable() {
String state = Environment.getExternalStorageState();
return Environment.MEDIA_MOUNTED.equals(state);
}
}
Bước 4: Manifest (androidManifest.xml)
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
package="app.com.sample">
<!-- Chỉ cần cho Android 9 trở xuống -->
<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>
Chạy ứng dụng
Kết nối thiết bị, nhấn Run. Nhập văn bản → nhấn LƯU → nhấn ĐỌC để kiểm tra.

Các đường dẫn quan trọng
| Phương thức | Đường dẫn | Cần quyền | Ghi chú |
|---|---|---|---|
getExternalFilesDir() | /Android/data/pkg/files/ | Không (API 19+) | Tự xóa khi uninstall app |
getExternalCacheDir() | /Android/data/pkg/cache/ | Không | Hệ thống có thể xóa khi thiếu dung lượng |
Environment.getExternalStorageDirectory() | /sdcard/ | CÓ (READ/WRITE_EXTERNAL_STORAGE) | Deprecated API 29+, bị chặn API 30+ |
Best Practice hiện nay
- Ưu tiên
getExternalFilesDir()- không cần xin quyền, an toàn - Dùng MediaStore API cho media (ảnh, video, audio) muốn chia sẻ
- Dùng Storage Access Framework (SAF) để người dùng chọn thư mục/file tùy ý
- Tránh dùng đường dẫn cứng "/sdcard/"