File dir = new File(Environment.getExternalStorageDirectory() + "/MyApp/MyFolder");
if (dir.isDirectory()) {
File file = new File(card.imagePath); // 疑似路徑錯誤
file.delete();
}
card.imagePath 是絕對路徑?是否包含在 dir 之下?Log.d("DELETE", "Target: " + file.getAbsolutePath() + " Exists: " + file.exists())。<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>getExternalFilesDir())無需權限;訪問共享目錄需 MANAGE_EXTERNAL_STORAGE(特殊權限,審核嚴格)或使用 MediaStore API。MediaPlayer、ImageView 或其他進程讀取,刪除會失敗。需先釋放資源。file.delete() 返回 boolean,務必檢查:if (!file.delete()) Log.e("DELETE", "Failed: " + file.getAbsolutePath())。// 使用 MediaStore 刪除共享媒體檔案(需用戶授權)
ContentResolver resolver = getContentResolver();
Uri collection = MediaStore.Files.getContentUri(MediaStore.VOLUME_EXTERNAL_PRIMARY);
String selection = MediaStore.MediaColumns.RELATIVE_PATH + "=?";
String[] selectionArgs = new String[]{"MyApp/MyFolder/"};
int deletedRows = resolver.delete(collection, selection, selectionArgs);
Log.d("DELETE", "Deleted rows: " + deletedRows);
此方式無需 WRITE_EXTERNAL_STORAGE,符合分區儲存規範。
File file = new File(getExternalFilesDir("MyFolder"), "image.jpg");
boolean success = file.delete();
// 或批量刪除
File dir = getExternalFilesDir("MyFolder");
if (dir != null) {
for (File f : dir.listFiles()) f.delete();
}
刪除失敗 90% 因路徑錯誤或權限不足。優先使用應用專屬目錄(getExternalFilesDir())簡化權限管理;必須操作共享目錄時,Android 10+ 必須遷移至 MediaStore API,舊版本確保 Manifest 權限與動態申請雙重保障。