我得到了

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

当前回答

在我的例子中,错误出现在行上

      target.createNewFile();

因为我不能在sd卡上创建一个新文件,所以我不得不使用DocumentFile方法。

      documentFile.createFile(mime, target.getName());

对于上述问题,可以用这种方法来解决,

    fos=context.getContentResolver().openOutputStream(documentFile.getUri());

看看这个帖子, 如何使用新的SD卡访问API为Android 5.0(棒棒糖)?

其他回答

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

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

:

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

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

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

添加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">

在manifest中添加权限。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_INTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

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

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

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

点击这里阅读更多。

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

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