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

前端 未结 1 329
日久生厌
日久生厌 2021-01-05 13:34

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 c

相关标签:
1条回答
  • 2021-01-05 14:34

    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;
    }
    
    0 讨论(0)
提交回复
热议问题