我得到了

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

当前回答

请注意解决方案:

<application ...
    android:requestLegacyExternalStorage="true" ... >

是临时的,迟早你的应用程序应该迁移到使用范围存储。

在Android 10中,你可以使用建议的解决方案来绕过系统限制,但在Android 11 (R)中,必须使用范围存储,如果你继续使用旧的逻辑,你的应用程序可能会崩溃!

这个视频可能会很有帮助。

其他回答

Android 10 (API 29)引入了作用域存储。更改清单以请求遗留存储并不是长期解决方案。

当我用context.getExternalFilesDir(null)替换我以前的Environment.getExternalStorageDirectory()实例(API 29已弃用)时,我修复了这个问题。

注意,如果存储位置不可用,context.getExternalFilesDir(type)可以返回null,因此无论何时检查是否具有外部权限,都要检查这一点。

点击这里阅读更多。

谷歌在Android Q上有一个新功能:外部存储的过滤视图。一个快速的修复方法是在AndroidManifest.xml文件中添加以下代码:

<manifest ... >
    <!-- This attribute is "false" by default on apps targeting Android Q. -->
    <application android:requestLegacyExternalStorage="true" ... >
     ...
    </application>
</manifest>

你可以在这里阅读更多信息:https://developer.android.com/training/data-storage/use-cases

编辑:我开始得到反对票,因为这个答案是过时的安卓11。看到答案的同学请点击上面的链接阅读说明。

我也有同样的问题……<uses-permission在错误的地方。这是正确的:

 <manifest>
        <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
        ...
        <application>
            ...
            <activity> 
                ...
            </activity>
        </application>
    </manifest> 

users -permission标记需要在application标记之外。

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

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

我有同样的问题(API >= 23)。

解决方案https://stackoverflow.com/a/13569364/1729501对我有用,但断开应用程序进行调试是不实际的。

我的解决方案是在Windows上安装合适的adb设备驱动程序。谷歌USB驱动程序不适用于我的设备。

步骤1:下载适合您的设备品牌的adb驱动程序。

步骤2:进入设备管理器->其他设备->查找带有“adb”字样的条目->选择更新驱动程序->在步骤1中给出位置