我得到了

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

当前回答

我使用下面的过程来处理android 11和targetapi30的情况

作为预先创建的文件dir根据范围存储在我的情况下根目录文件//<图像/视频…按照要求> 复制选中的文件,并在从我的外部存储选择时复制缓存目录中的文件 然后在一次上传(在我的发送/上传按钮点击)复制文件从缓存目录到我的范围存储目录,然后做我的上传过程

使用这个解决方案,因为在播放商店上传应用程序时,它会生成MANAGE_EXTERNAL_STORAGE权限的警告,在我的情况下,有时会被播放商店拒绝。

同样,我们使用目标API 30,所以我们不能从内部存储共享或转发文件到应用程序

其他回答

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

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

:

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

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

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

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

我使用下面的过程来处理android 11和targetapi30的情况

作为预先创建的文件dir根据范围存储在我的情况下根目录文件//<图像/视频…按照要求> 复制选中的文件,并在从我的外部存储选择时复制缓存目录中的文件 然后在一次上传(在我的发送/上传按钮点击)复制文件从缓存目录到我的范围存储目录,然后做我的上传过程

使用这个解决方案,因为在播放商店上传应用程序时,它会生成MANAGE_EXTERNAL_STORAGE权限的警告,在我的情况下,有时会被播放商店拒绝。

同样,我们使用目标API 30,所以我们不能从内部存储共享或转发文件到应用程序

请注意解决方案:

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

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

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

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

谷歌在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。看到答案的同学请点击上面的链接阅读说明。