我得到了

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

当前回答

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),然后它就工作了!

我也有同样的问题,但没有一个建议有用。但我发现了一个有趣的原因,那就是在实体设备Galaxy Tab上。

当USB存储打开时,外部存储的读写权限没有任何影响。 只要关闭USB存储,并使用正确的权限,你就会有问题解决。

奇怪的是,在我的newFile之前加上斜杠“/”后,我的问题就解决了。我改了这个:

File myFile= new File(Environment.getExternalStorageDirectory() + "newFile");

:

File myFile= new File(Environment.getExternalStorageDirectory() + "/newFile");

更新: 正如评论中提到的,正确的做法是:

File myFile= new File(Environment.getExternalStorageDirectory(), "newFile");

将此添加到清单,但此权限具有谷歌播放策略。

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