我得到了

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

当前回答

事实证明,这是一个愚蠢的错误,因为我的手机仍然连接着台式电脑,并且没有意识到这一点。

所以我不得不关掉USB连接,一切都很好。

其他回答

我的问题是“TargetApi(23)”,这是需要的,如果你的minSdkVersion是低于23。

因此,我已请求以下代码片段的权限

protected boolean shouldAskPermissions() {
    return (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1);
}

@TargetApi(23)
protected void askPermissions() {
    String[] permissions = {
            "android.permission.READ_EXTERNAL_STORAGE",
            "android.permission.WRITE_EXTERNAL_STORAGE"
    };
    int requestCode = 200;
    requestPermissions(permissions, requestCode);
}

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
// ...
    if (shouldAskPermissions()) {
        askPermissions();
    }
}

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

所以正确的做法是:-

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

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

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

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

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

除了所有的答案,确保你没有把你的手机用作USB存储器。

我在启用USB存储模式的HTC Sensation上也遇到了同样的问题。我仍然可以调试/运行应用程序,但我不能保存到外部存储。

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

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