| 存儲類型 | 路徑獲取方式 | 權限需求 | 特點 |
|---|---|---|---|
| 內部存儲 (App 專屬) | context.filesDir / context.cacheDir | 無需權限 | App 協載自動刪除、其他 App 不可訪問、空間有限 |
| 外部存儲 (公共/App 專屬) | Environment.getExternalStorageDirectory() (公共)context.getExternalFilesDir() (App 專屬) | Android 10 以下需 WRITE_EXTERNAL_STORAGEAndroid 10+ 採用分區存儲,公共目錄需 MediaStore | 空間大、用戶可見、可被其他 App 訪問 (視版本而定) |
| 可移動 SD 卡 | Context.getExternalFilesDirs() 第二個元素起 | 同外部存儲 | 物理可移除,需檢測掛載狀態 |
// SD 卡是否掛載可用 boolean mounted = Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState()); // 內部存儲根目錄 File internalRoot = context.getFilesDir(); // /data/data/pkg/files File internalCache = context.getCacheDir(); // /data/data/pkg/cache // 外部存儲 (App 專屬,協載自動清理) File extFiles = context.getExternalFilesDir(null); // /sdcard/Android/data/pkg/files File extCache = context.getExternalCacheDir(); // /sdcard/Android/data/pkg/cache // 外部公共目錄 (圖片、下載等) — Android 10+ 建議用 MediaStore File picDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); // 多卷外部存儲 (含 SD 卡) File[] allExtDirs = context.getExternalFilesDirs(null); // [0] 主共享存儲, [1...] SD 卡等
// 路徑
String absPath = file.getAbsolutePath();
String relPath = file.getPath(); // 相對路徑
String name = file.getName(); // 文件名
String parent = file.getParent(); // 父目錄路徑
// 判斷
boolean exists = file.exists();
boolean isDir = file.isDirectory();
boolean isFile = file.isFile();
// 創建 / 刪除 / 重命名
boolean created = file.createNewFile(); // 創建文件
boolean mkdirs = file.mkdirs(); // 創建多級目錄
boolean deleted = file.delete(); // 刪除 (目錄需為空)
boolean renamed = file.renameTo(newFile); // 重命名/移動
// 列舉
File[] children = file.listFiles(); // 返回 File[] 或 null
String[] names = file.list(); // 僅名稱
// 過濾列舉
File[] images = dir.listFiles((d, n) -> n.endsWith(".jpg") || n.endsWith(".png"));
// 寫入 — MODE_PRIVATE 覆蓋,MODE_APPEND 追加
try (FileOutputStream fos = context.openFileOutput("note.txt", Context.MODE_PRIVATE)) {
fos.write("Hello Internal Storage".getBytes(StandardCharsets.UTF_8));
}
// 讀取
StringBuilder sb = new StringBuilder();
try (FileInputStream fis = context.openFileInput("note.txt");
BufferedReader br = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8))) {
String line;
while ((line = br.readLine()) != null) sb.append(line).append('\n');
}
String content = sb.toString();
// 需 Manifest:File file = new File(context.getExternalFilesDir(null), "data.json"); try (FileOutputStream fos = new FileOutputStream(file)) { fos.write(jsonBytes); }
<application android:requestLegacyExternalStorage="true"> 繼續舊行為requestLegacyExternalStorage 支持getExternalFilesDir()) 繼續免權限直讀寫MANAGE_EXTERNAL_STORAGE (特殊權限,上架需審核)ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DISPLAY_NAME, "photo.jpg");
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.RELATIVE_PATH, Environment.DIRECTORY_PICTURES + "/MyApp");
Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
try (OutputStream os = context.getContentResolver().openOutputStream(uri)) {
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, os);
}
String[] projection = {MediaStore.Images.Media._ID, MediaStore.Images.Media.DISPLAY_NAME, MediaStore.Images.Media.DATA};
String selection = MediaStore.Images.Media.RELATIVE_PATH + " LIKE ?";
String[] args = {"%/MyApp/%"};
try (Cursor cursor = resolver.query(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection, selection, args, null)) {
while (cursor.moveToNext()) {
long id = cursor.getLong(0);
String name = cursor.getString(1);
// 獲取內容 URI: ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id)
}
}
MODE_PRIVATE (0):默認,覆蓋寫入,僅當前 App 可讀MODE_APPEND (32768):追加寫入MODE_WORLD_READABLE, MODE_WORLD_WRITEABLE (API 17+ 拋 SecurityException) — 跨應用共享請用 ContentProvider 或 MediaStore/** 將字符串保存到內部存儲 */
public static void saveInternal(Context ctx, String fileName, String content) throws IOException {
try (FileOutputStream fos = ctx.openFileOutput(fileName, Context.MODE_PRIVATE)) {
fos.write(content.getBytes(StandardCharsets.UTF_8));
}
}
/** 從內部存儲讀取字符串 */
public static String readInternal(Context ctx, String fileName) throws IOException {
try (FileInputStream fis = ctx.openFileInput(fileName);
BufferedReader br = new BufferedReader(new InputStreamReader(fis, StandardCharsets.UTF_8))) {
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) sb.append(line).append('\n');
return sb.toString();
}
}
/** 遞歸刪除目錄 */
public static boolean deleteRecursive(File file) {
if (file.isDirectory()) {
File[] children = file.listFiles();
if (children != null) for (File child : children) deleteRecursive(child);
}
return file.delete();
}
/sdcard/),務必用 API 獲取BufferedInputStream/OutputStream,避免一次性載入記憶體context.cacheDir 系統可能自動清理,但不保證及時/ \ : * ? " < > | 等非法字符MediaScannerConnection.scanFile() 讓圖庫及時刷新Android 文件系統經歷了從「完全開放」到「分區存儲」的重大演進。現代開發應以 內部存儲為首選 (私密、免權限、自動清理);需用戶可見或跨應用共享時,優先使用 MediaStore;僅在極少數場景 (文件管理器、備份工具) 申請 MANAGE_EXTERNAL_STORAGE。掌握版本差異、善用 Context API 與 ContentResolver,才能寫出生產級穩健的存儲代碼。