Android6使用FIleOutputStream 或 FIleInputStream时:
报错Permission Denied
open failed: EACCES (Permission denied)
...
Caused by: libcore.io.ErrnoException: open failed: EACCES (Permission denied)
解决办法:
①在AndroidManifest.xml文件中增加相关读取权限:
(只写一个就行,Android会默认添加其相对的另外一个权限)
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
②Android 10的版本,可以添加android:requestLegacyExternalStorage="true"解决:
<manifest ... >
<!-- This attribute is "false" by default on apps targeting Android Q. -->
<application android:requestLegacyExternalStorage="true" ... >
...
</application>
</manifest>
③ 动态申请存储权限(但是需要用户点击同意)
(相对应的,开发自己使用的app时可以进应用设置/权限设置里手动打开app 的W、R权限)
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
/**
* Checks if the app has permission to write to device storage
*
* If the app does not has permission then the user will be prompted to grant permissions
*
* @param activity
*/
public static void verifyStoragePermissions(Activity activity) {
// Check if we have write permission
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
);
}
}
④ Android 6:需要把要修改的文件的路径改为 data/data/包名/cache
只有这个办法在Android 6 上解决了我的问题。