Android - How to use new Storage Access Framework

2020-03-03 06:51发布

问题:

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.

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 ?

回答1:

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