打开失败:Android6.0.1系统应用程序中的EACCES权限被拒绝

问题描述

我开发了一个安卓系统应用程序来将文件从 /sdcard/download/test.txt 复制到 /cache/xyz/ 位置。

我可以将文件复制到 /cache/ ,但 bot 复制到 /cache/xyz/ location ,

出现以下错误

java.io.FileNotFoundException:/cache/xyz/test.txt:打开失败:EACCES(权限被拒绝)

File packageFile = new File(Environment.getDownloadCacheDirectory() + "/xyz/test.txt");
                        File downloadedFile = new File(Environment.getExternalStorageDirectory() + "/test.txt");
                        if (packageFile.exists()) {
                            Log.d(TAG,"TEST -> File in Cache Exists");
                            
                        } else {
                            Log.d(TAG,"TEST -> File in Cache is Empty");
                        }
                        packageFile.canWrite();
                        if (downloadedFile.exists()) {
                            Log.d(TAG,"TEST -> packageFile in downloadedFile Exists");

                            FileChannel source = null;
                            FileChannel dest = null;

                            try {
                                source = (new FileInputStream(downloadedFile)).getChannel();
                                dest = (new FileOutputStream(packageFile)).getChannel();
        count += dest.transferFrom(source,count,size-count);

                               

                               
                            catch (Exception e) {
                                Log.d(TAG,"TEST -> Failed to copy update file into internal storage: " + e);
                            }

                           
                        } else {
                            Log.d(TAG,"TEST -> File DO NOT Exists");

                        }

清单:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

解决方法

对于 API 23+,您需要请求读/写权限,即使它们已经在您的清单中。

// 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
        );
    }
}

通过:Exception 'open failed: EACCES (Permission denied)' on Android