我得到了

open failed: EACCES(权限被拒绝)

myOutput = new FileOutputStream(outFileName);

我检查了根目录,并尝试了android.permission.WRITE_EXTERNAL_STORAGE。

我该如何解决这个问题?

try {
    InputStream myInput;

    myInput = getAssets().open("XXX.db");

    // Path to the just created empty db
    String outFileName = "/data/data/XX/databases/"
            + "XXX.db";

    // Open the empty db as the output stream
    OutputStream myOutput = new FileOutputStream(outFileName);

    // Transfer bytes from the inputfile to the outputfile
    byte[] buffer = new byte[1024];
    int length;
    while ((length = myInput.read(buffer)) > 0) {
        myOutput.write(buffer, 0, length);
    }

    // Close the streams
    myOutput.flush();
    myOutput.close();
    myInput.close();
    buffer = null;
    outFileName = null;
}
catch (IOException e1) {
    // TODO Auto-generated catch block
    e1.printStackTrace();
}

当前回答

除了所有的答案,如果客户端使用Android 6.0, Android为(Marshmallow)增加了新的权限模型。

技巧:如果你的目标版本是22或以下,你的应用程序将在安装时请求所有权限,就像它在任何运行棉花糖以下操作系统的设备上一样。如果你在模拟器上尝试,那么从android 6.0开始,你需要显式地去设置->应用程序-> YOURAPP ->权限,如果你已经给了任何权限,改变权限。

其他回答

如果你有一个根设备,可以通过以下adb命令绕过6.0后的存储权限强制执行:

root@msm8996:/ # getenforce
getenforce
Enforcing
root@msm8996:/ # setenforce 0
setenforce 0
root@msm8996:/ # getenforce
getenforce
Permissive

我在Galaxy S5 (android 6.0.1)上尝试在DCIM/camera文件夹中写入图像时遇到了同样的错误,我发现只有这个文件夹是受限制的。我可以简单地写入DCIM/任何文件夹,但不是在相机。 这应该是基于品牌的限制/定制。

我使用下面的过程来处理android 11和targetapi30的情况

作为预先创建的文件dir根据范围存储在我的情况下根目录文件//<图像/视频…按照要求> 复制选中的文件,并在从我的外部存储选择时复制缓存目录中的文件 然后在一次上传(在我的发送/上传按钮点击)复制文件从缓存目录到我的范围存储目录,然后做我的上传过程

使用这个解决方案,因为在播放商店上传应用程序时,它会生成MANAGE_EXTERNAL_STORAGE权限的警告,在我的情况下,有时会被播放商店拒绝。

同样,我们使用目标API 30,所以我们不能从内部存储共享或转发文件到应用程序

2022 Kotlin请求许可的方式:

private val writeStoragePermissionResult =
   registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions()) { permissions ->}

private fun askForStoragePermission(): Boolean =
   if (hasPermissions(
           requireContext(),
           Manifest.permission.READ_EXTERNAL_STORAGE,
           Manifest.permission.WRITE_EXTERNAL_STORAGE
       )
   ) {
       true
   } else {
       writeStoragePermissionResult.launch(
           arrayOf(
               Manifest.permission.READ_EXTERNAL_STORAGE,
               Manifest.permission.WRITE_EXTERNAL_STORAGE,
           )
       )
       false
   }

fun hasPermissions(context: Context, vararg permissions: String): Boolean = permissions.all {
    ActivityCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}

我在init中/data/下创建了一个文件夹。rc(在Nexus 7上摆弄aosp),就遇到了这个问题。

结果证明,给文件夹rw(666)权限是不够的,它必须是rwx(777),然后它就工作了!