public boolean hasExternalStorage() {
return Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState());
}
// 獲取可用存儲目錄(優先外部,回退內部)
public File getAppStorageDir(Context context, String dirName) {
File file = new File(context.getExternalFilesDir(null), dirName);
if (!file.exists() && !hasExternalStorage()) {
file = new File(context.getFilesDir(), dirName); // 內部存儲
}
if (!file.exists()) file.mkdirs();
return file;
}
File photoFile = File.createTempFile("IMG_", ".jpg", getAppStorageDir(this, "photos"));
Uri photoUri = FileProvider.getUriForFile(this, getPackageName() + ".provider", photoFile);
intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
需在 Manifest 宣告 FileProvider。
// 讀取舊 SP
SharedPreferences oldSp = getSharedPreferences("login", MODE_PRIVATE);
String token = oldSp.getString("token", "");
// 寫入新文件(內部存儲,應用專屬,用戶不可見)
File tokenFile = new File(getFilesDir(), "auth_token.txt");
try (FileWriter fw = new FileWriter(tokenFile)) {
fw.write(token);
}
// 登錄時讀取
String savedToken = new String(Files.readAllBytes(tokenFile.toPath()));
/data/data/pkg/files/)無需權限,用戶無法手動清除