Android Studio获得错误IOException:为Android SDK创建文件时不允许操作31
我正在尝试在外部存储上创建一个文件,但我会得到“ 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" />
我还添加了Check sexspermission,然后在创建我已将CompileSdk和Targetsdk版本的文件
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
);
}
}
设置为31中。即使尝试所有这些,我也无法创建一个目录或一个目录或一个在外部存储上文件。我该如何解决这个问题?
I am trying to create a file on external storage but I am getting "IOException: Operation not permitted" error. Below is my code
File file = new File(Environment.getExternalStorageDirectory() + "/dummy.txt");
if (!file.exists()){
file.createNewFile();
}
Below are the permissions I have added to manifest file
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
I have also added checkSelfPermission before creating the file
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
);
}
}
I have set compilesdk and targetsdk version to 31. Even after trying all of this, I am not able to create a directory or a file on external storage. How can I solve this issue?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
根据Google文档
从Android 11开始,应用程序无法在外部存储
上创建自己的应用程序特定目录,也无法创建文件,因此要解决此问题,您可以在任何其他任何内容中创建文件例如,类似下载目录的目录,您的代码看起来像这样:According to google documentation
Starting in Android 11, apps cannot create their own app-specific directory on external storage
, and also the same thing for creating files, so to fix this you can create the file in any other directory like downloads directory for example, your code will look like this: