| 位置 | API | 權限 | 存取範圍 | 適用場景 | 備份/卸載行為 |
|---|---|---|---|---|---|
| res/raw | `getResources().openRawResource(R.raw.xxx)` | 無 | 唯讀、打包在 APK | 預設設定檔、預置資料庫、靜態模板 | App 更新覆蓋、卸載刪除 |
| assets/ | `getAssets().open("file")` | 無 | 唯讀、目錄結構保留、打包在 APK | 字體、HTML/CSS/JS、大型預置資料 (配合複製到內部儲存) | 同 raw |
| 內部儲存 `/data/data/pkg/files/` | `openFileOutput()` `openFileInput()` `context.filesDir` `context.cacheDir` | 無 (私有) | **完全私有**,其他 App 不可見 (除非 `MODE_WORLD_READABLE` 已棄用) | 用戶資料、Token、資料庫、快取、私密圖片 | **卸載自動刪除**;備份含此目錄 (Auto Backup) |
| 外部儲存 (舊) `/sdcard/` | `Environment.getExternalStorageDirectory()` `File` API | `READ/WRITE_EXTERNAL_STORAGE` | **全域可見** (Android 10 前) | 相片、下載、匯出檔案、分享檔案 | 卸載**不刪除** (用戶可見) |
| 外部儲存 (Scoped Storage) Android 10+ (API 29+) | `context.getExternalFilesDir()` `context.getExternalCacheDir()` `MediaStore` API `StorageAccessFramework` (SAF) | **自有目錄免權限** 媒體檔需 `READ_MEDIA_*` 其他檔需 SAF 用戶授權 | **應用專屬目錄** 私有; 公共媒體庫 (MediaStore) 需權限; 任意目錄需 SAF 選擇器 | 應用專屬檔案、用戶導出媒體、文件選擇器 | 應用專屬目錄**卸載刪除**;MediaStore 檔案保留 |
// raw
String readRaw(Context ctx, @RawRes int resId) throws IOException {
try (InputStream is = ctx.getResources().openRawResource(resId);
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
return br.lines().collect(Collectors.joining("\n"));
}
}
// assets (支援子目錄)
String readAsset(Context ctx, String fileName) throws IOException {
try (InputStream is = ctx.getAssets().open(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8))) {
return br.lines().collect(Collectors.joining("\n"));
}
}
// 寫入
void writeInternal(Context ctx, String fileName, String content) throws IOException {
try (FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE);
OutputStreamWriter osw = new OutputStreamWriter(fos, StandardCharsets.UTF_8);
BufferedWriter bw = new BufferedWriter(osw)) {
bw.write(content);
}
}
// 讀取
String readInternal(Context ctx, String fileName) throws IOException {
try (FileInputStream fis = ctx.openFileInput(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8))) {
return br.lines().collect(Collectors.joining("\n"));
}
}
// 列出/刪除
String[] list = ctx.fileList();
ctx.deleteFile(fileName);
File filesDir = ctx.getFilesDir(); // 任意 File 操作
File cacheDir = ctx.getCacheDir(); // 系統可隨時清理
// 寫入
void writeExternalAppDir(Context ctx, String fileName, byte[] data) throws IOException {
File dir = ctx.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS); // 或 null 為根目錄
File file = new File(dir, fileName);
try (FileOutputStream fos = new FileOutputStream(file)) {
fos.write(data);
}
}
// 讀取
byte[] readExternalAppDir(Context ctx, String fileName) throws IOException {
File file = new File(ctx.getExternalFilesDir(null), fileName);
try (FileInputStream fis = new FileInputStream(file)) {
return fis.readAllBytes();
}
}
// 插入圖片 (Android 10+)
Uri insertImage(Context ctx, Bitmap bitmap, String displayName) throws IOException {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, displayName);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/MyApp");
Uri uri = ctx.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try (OutputStream os = ctx.getContentResolver().openOutputStream(uri)) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
}
return uri;
}
// 查詢圖片
Cursor queryImages(Context ctx) {
String[] proj = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATA};
return ctx.getContentResolver().query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, proj, null, null, null);
}
// 開啟目錄選擇器 (建立/寫入檔案)
Intent intent = new Intent(Intent.ACTION_CREATE_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TITLE, "notes.txt");
startActivityForResult(intent, REQ_CREATE_FILE);
// 接收結果
@Override
protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
if (requestCode == REQ_CREATE_FILE && resultCode == RESULT_OK && data != null) {
Uri uri = data.getData();
// 取得可持久化的 URI 權限
getContentResolver().takePersistableUriPermission(uri, Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// 寫入
try (OutputStream os = getContentResolver().openOutputStream(uri)) {
os.write("Hello SAF".getBytes(StandardCharsets.UTF_8));
}
}
}
Android 儲存體模型經歷「全域共享 → Scoped Storage 隔離」演進。理解 **私有 vs 共享、卸載行為、權限模型、API 版本差異**,並採用 **內部儲存為主、MediaStore 存媒體、SAF 交互用戶檔案** 的分層策略,即可構建相容全版本、符合隱私規範、用戶體驗良好的文件管理功能。