Android-如何使用新的Storage Access Framework将文件复制到外部SD卡 [英] Android - How to use new Storage Access Framework to copy files to external sd card

查看:265
本文介绍了Android-如何使用新的Storage Access Framework将文件复制到外部SD卡的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm implementing a file browser feature in my app. I know how to gain persistent permission for the external sd card using the ACTION_OPEN_DOCUMENT_TREE intent and how to create folders and delete files/folders using the DocumentFile class.

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

I can't however find a way to copy/move a file to an external sd card folder. Can you point me to the right direction ?

推荐答案

我在SO上使用了很多示例来弄清楚.我对音乐文件的解决方案:

I have figured it out using lots of examples on SO. My solution for music files:

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

这篇关于Android-如何使用新的Storage Access Framework将文件复制到外部SD卡的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆