繁体   English   中英

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

[英]Android - How to use new Storage Access Framework to copy files to external sd card

我正在我的应用程序中实现文件浏览器功能。 我知道如何使用ACTION_OPEN_DOCUMENT_TREE意图获得外部SD卡的持久权限,以及如何使用DocumentFile类创建文件夹和删除文件/文件夹。

但是,我找不到将文件复制/移动到外部SD卡文件夹的方法。 你能指出我正确的方向吗?

我已经在SO上使用了很多例子。 我的音乐文件解决方案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM