【问题标题】:Copy file from path to Path in Android 11在 Android 11 中将文件从路径复制到路径
【发布时间】:2021-09-19 11:22:25
【问题描述】:

希望你没事。

在我完成所有步骤后,在 Android 11 中获取权限存储,现在我可以创建文件、将文件从资产复制到任何文件夹或删除文件。

我只是在尝试从路径复制文件时遇到问题,问题是我发现输出文件为空。

仅在这方面我需要帮助,我希望你能帮助我并告诉我我的代码中有什么错误,并提前致谢。

复制我正在使用:

Uri muri = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3Aagora%2file.txt");
Uri uri2 = Uri.parse("content://com.android.externalstorage.documents/tree/primary%3AAlarms");
DocumentFile mfile = DocumentFile.fromTreeUri(MainActivity.this, muri);
DocumentFile mfile1 = DocumentFile.fromTreeUri(MainActivity.this, uri2);
mfile1 = mfile1.createFile("file/txt", "file.txt");
uri2 = mfile1.getUri();
if (copyFileFromUri2(MainActivity.this, muri, uri2)) {
    showMessage("file copied successfully");
} else {
    showMessage("failed to copy the file !");
}

方法:

public boolean copyFileFromUri2(Context context, Uri fileUri, Uri targetUri)
{
    InputStream fis = null;
    OutputStream fos = null;
    try {
        ContentResolver content = context.getContentResolver();
        fis = content.openInputStream(fileUri);
        fos = content.openOutputStream(targetUri);
        byte[] buff = new byte[1024];
        int length = 0;
        while ((length = fis.read(buff)) > 0) {
            fos.write(buff, 0, length);
        }
    } catch (IOException e) {
        return false;
    } finally {
        if (fis != null) {
            try {
                fis.close();
            } catch (IOException e) {
                return false;
            }
        }
        if (fos != null) {
            try {
                fos.close();
            } catch (IOException e) {
                return false;
            }
        }
    }
    return true;
}

【问题讨论】:

    标签: java storage


    【解决方案1】:

    您可以尝试如下初始化OutputStream os:

    fos = new BufferedOutputStream( content.openOutputStream(targetUri))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-07
      • 1970-01-01
      • 2020-08-15
      • 2022-10-17
      • 1970-01-01
      相关资源
      最近更新 更多