【Android报错】FileNotFoundException open failed:文件路径 EPERM (Operation not permitted)外部存储至根目录报错,Android外部存储权限动态获取问题

2023-03-07,,

报错:FileNotFoundException open failed: XXXXXXX EPERM (Operation not permitted)

查了下,大概原因是因为权限的问题。(小白学Android,Android文档查起来还有点吃力,就直接谷歌+百度。)

但是Manifest里该加的权限都加了。还application增加了android:requestLegacyExternalStorage="true",表示没用。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS" tools:ignore="ProtectedPermissions" />

Android 6.0以后,Android对权限管理更严格了。试了几种解决办法,都不算我想要的。本意是想存储到SD卡的根路径下。

算了,先忽略了。继续往下学习吧。

解决:

自定义存储方法(原代码)

    public void saveIMG(){
BufferedInputStream bis=null;
BufferedOutputStream bos=null;
try {
//获取APP内存储路径,模拟器可行
// ContextWrapper cw = new ContextWrapper(getApplicationContext());
// File sdkPath = cw.getExternalFilesDir(Environment.DIRECTORY_PICTURES); //获取public存储路径,模拟器可行。真机需要动态权限
// File sdkPath=Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES); //获取根路径,不可行。增加动态获取外部存储读取权限后,真机运行,可行。
File sdkPath=Environment.getExternalStorageDirectory(); Log.v("hehe","sdkPath:"+sdkPath.getPath());
file =new File(sdkPath,"test.jpeg");
//读取图片
@SuppressLint("ResourceType") InputStream is= getResources().openRawResource(R.drawable.kelala);
//存储图片
OutputStream io=new FileOutputStream(file); bis=new BufferedInputStream(is);
bos=new BufferedOutputStream(io); int len=0;
byte[] buf=new byte[1024];
while ((len=bis.read(buf))!=-1){ bos.write(buf,0,len);
bos.flush();
}
Log.v("hehe","读取和存储buffer");
Toast.makeText(OutStore.this,"存储成功!!!!!",Toast.LENGTH_LONG).show(); } catch (FileNotFoundException e) {
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}finally {
if (bis!=null){
try {
bis.close();
} catch (IOException e) {
e.printStackTrace();
}
} if (bos!=null){
try {
bos.close();
} catch (IOException e) {
e.printStackTrace();
}
} } }

调用自定义存储方法的Activity里增加外部存储动态权限获取的代码:

//需要动态授外部存储权限。模拟器不弹动态权限授权对话框,晚点看下什么问题吧
int REQUEST_EXTERNAL_STORAGE = 1;
String[] PERMISSIONS_STORAGE = {"android.permission.READ_EXTERNAL_STORAGE","android.permission.WRITE_EXTERNAL_STORAGE" };
ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE,REQUEST_EXTERNAL_STORAGE);

【Android报错】FileNotFoundException open failed:文件路径 EPERM (Operation not permitted)外部存储至根目录报错,Android外部存储权限动态获取问题的相关教程结束。

《【Android报错】FileNotFoundException open failed:文件路径 EPERM (Operation not permitted)外部存储至根目录报错,Android外部存储权限动态获取问题.doc》

下载本文的Word格式文档,以方便收藏与打印。