安卓 - 如何使用新的存储访问框架将文件复制到外部SD卡

8
我正在实现一个文件浏览器功能的应用程序。我知道如何使用ACTION_OPEN_DOCUMENT_TREE意图获得外部SD卡的持久权限,并且知道如何使用DocumentFile类创建文件夹和删除文件/文件夹。
但是,我无法找到一种将文件复制/移动到外部SD卡文件夹的方法。你能指导我正确的方向吗?

1
我无法找到一种将文件复制/移动到外部SD卡文件夹的方法--除了通过getExternalFilesDirs()(复数)等方式,您无法访问“外部SD卡文件夹”。您是否计划使用存储访问框架来询问用户要将东西复制到哪里?如果是这样,请使用Java I/O从源UriInputStream复制到目标UriOutputStream - CommonsWare
1
如果我使用Java文件系统,我没有权限修改次要SD卡。例如:创建文件夹:(new File(path))。mkdir();不起作用,但是利用新的SAF通过documentFile.createDirectory(name);(其中documentFile是使用DocumentFile.fromTreeUri(context,treeUri)创建的)可以工作。因此,我正在寻找一种使用DocumentsContract API复制文件的方法。 - Anonymous
2
正如我所指出的,获取原始文件的Uri,获取拟复制文件的Uri,在两个文件上打开流,并进行Java I/O操作。 我不记得Android当前发布版本中是否有内置的复制或移动操作。 - CommonsWare
1
非常好,谢谢! - Anonymous
1个回答

15

我已经通过 Stack Overflow 上的许多示例找到了解决方案。我的音乐文件解决方案:

     private String copyFile(String inputPath, String inputFile, Uri treeUri) {
    InputStream in = null;
    OutputStream out = null;
    String error = null;
    DocumentFile pickedDir = DocumentFile.fromTreeUri(getActivity(), treeUri);
    String extension = inputFile.substring(inputFile.lastIndexOf(".")+1,inputFile.length());

    try {
        DocumentFile newFile = pickedDir.createFile("audio/"+extension, inputFile);
        out = getActivity().getContentResolver().openOutputStream(newFile.getUri());
        in = new FileInputStream(inputPath + inputFile);

        byte[] buffer = new byte[1024];
        int read;
        while ((read = in.read(buffer)) != -1) {
            out.write(buffer, 0, read);
        }
        in.close();
        // write the output file (You have now copied the file)
        out.flush();
        out.close();

    } catch (FileNotFoundException fnfe1) {
        error = fnfe1.getMessage();
    } catch (Exception e) {
        error = e.getMessage();
    }
    return error;
}

1
inputPath 是什么? - Tushar Kshirsagar
@Tushar,你正在复制的文件当然 - Theo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接