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

时间:2016-03-15 22:19:24

标签: android android-external-storage storage-access-framework

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

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

1 个答案:

答案 0 :(得分:6)

我已经在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;
}