我得到了

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

当前回答

我也有同样的经历。我发现,如果你去设置->应用程序管理器->你的应用程序->权限->启用存储,它解决了这个问题。

其他回答

当您的应用程序属于系统应用程序时,它不能访问SD卡。

添加android:requestLegacyExternalStorage="true"到android Manifest中 它在SDK 29+的Android 10 (Q)上工作 或迁移Android X后。

 <application
    android:name=".MyApplication"
    android:allowBackup="true"
    android:hardwareAccelerated="true"
    android:icon=""
    android:label=""
    android:largeHeap="true"
    android:supportsRtl=""
    android:theme=""
    android:requestLegacyExternalStorage="true">

将文件存储在与应用程序目录无关的目录中受API 29+以上限制。因此,要生成一个新文件或创建一个新文件,使用你的应用程序目录,就像这样

所以正确的做法是:-

val file = File(appContext.applicationInfo.dataDir + File.separator + "anyRandomFileName/")

您可以将任何数据写入这个生成的文件!

上面的文件是可访问的,不会抛出任何异常,因为它位于您自己开发的应用程序的目录中。

另一个选项是android:requestLegacyExternalStorage="true"在清单应用程序标签,由Uriel建议,但它不是一个永久的解决方案!

请记住,即使您在清单中设置了所有正确的权限: 唯一允许第三方应用程序写入你的外部卡的地方是“他们自己的目录” (例如/ sdcard / Android /数据/) 试图写入其他地方:你会得到异常: EACCES(拒绝许可)

我希望下面的所有内容/数据都属于“内部存储”。但是,您应该能够写入/sdcard。