【问题标题】:copy file from /root/storage/emulated/0 fails on android从 /root/storage/emulated/0 复制文件在 android 上失败
【发布时间】:2017-09-13 14:22:50
【问题描述】:

我正在尝试将文件从设备上的某个位置复制到应用程序文件夹,并使用:

public static void copyFile(final String srcAbsolutePath, final String dstAbsolutePath) throws IOException {
        FileInputStream srcFileStream = null;
        FileOutputStream dstFileStream = null;
        try {
            srcFileStream = new FileInputStream(srcAbsolutePath);
            dstFileStream = new FileOutputStream(dstAbsolutePath);
            byte[] writeBytes = new byte[1024];

            int bytesCount;
            while ((bytesCount = srcFileStream.read(writeBytes)) > 0) {
                dstFileStream.write(writeBytes, 0, bytesCount);
            }
        } catch (IOException ex) {
            Log.e(TAG, "Failed to copy the file from src="+srcAbsolutePath+" to="+dstAbsolutePath, ex);
            throw ex;
        } finally {
            // close the streams
            if (srcFileStream != null) {
                srcFileStream.close();
            }

            if (dstFileStream != null) {
                dstFileStream.close();
            }
        }
    }

我遇到了这个错误:

Failed to copy the file from src=/root/storage/emulated/0/TestApp/1a5e67e1-c166-4a52-abb4-3de61898e109.pdf to=/data/user/0/com.myapp.package/files/78e6a56b-3141-4024-a3a1-f3f44ccc6dfb.pdf
                                                                      java.io.FileNotFoundException: /root/storage/emulated/0/TestApp/1a5e67e1-c166-4a52-abb4-3de61898e109.pdf (Permission denied)

我有以下权限:

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

我正在使用https://github.com/spacecowboy/NoNonsense-FilePicker 来选择文件(Uri)。

我在 AndroidManifest.xml 中有以下内容

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/nnf_provider_paths" />
    </provider>

如何修复错误?

【问题讨论】:

  • 嗯,这在大多数 Android 设备上应该是无效的路径,所以我对它崩溃并不感到惊讶。您需要弄清楚为什么该库会为您提供该价值。不过,您问题中的所有代码都与此无关。
  • 确保文件剂量存在,你有java.io.FileNotFoundException警告

标签: java android android-permissions file-copying nononsense-filepicker


【解决方案1】:

终于在NoNonsense-FilePicker(getFileForUri)中找到了一个实用程序:

https://github.com/spacecowboy/NoNonsense-FilePicker/blob/master/library/src/main/java/com/nononsenseapps/filepicker/Utils.java

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-01-09
    • 2020-05-19
    • 1970-01-01
    • 2022-11-09
    • 1970-01-01
    • 1970-01-01
    • 2014-06-30
    • 2018-11-05
    相关资源
    最近更新 更多