我正在嘗試在外部存盤上創建檔案,但出現“IOException:不允許操作”錯誤。下面是我的代碼
File file = new File(Environment.getExternalStorageDirectory() "/dummy.txt");
if (!file.exists()){
file.createNewFile();
}
以下是我添加到清單檔案的權限
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
在創建檔案之前,我還添加了 checkSelfPermission
if(Build.VERSION.SDK_INT >= 23) {
int permission = ActivityCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (permission != PackageManager.PERMISSION_GRANTED) {
// We don't have permission so prompt the user
ActivityCompat.requestPermissions(
activity,
PERMISSIONS_STORAGE,
REQUEST_EXTERNAL_STORAGE
);
}
}
我已將 compilesdk 和 targetsdk 版本設定為 31。即使嘗試了所有這些,我也無法在外部存盤上創建目錄或檔案。我該如何解決這個問題?
uj5u.com熱心網友回復:
根據谷歌檔案Starting in Android 11, apps cannot create their own app-specific directory on external storage,創建檔案也是一樣的,所以要解決這個問題,您可以在任何其他目錄(例如下載目錄)中創建檔案,您的代碼將如下所示:
File file = new File(Environment.getExternalStorageDirectory() "/" Environment.DIRECTORY_DOWNLOADS "/dummy.txt");
if (!file.exists()){
file.createNewFile();
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/493445.html
上一篇:有狀態的條件在反應中不起作用
