8

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 ?

Anonymous
  • 4,470
  • 3
  • 36
  • 67
  • 1
    "I can't however find a way to copy/move a file to an external sd card folder" -- you don't have access to an "external sd card folder", other than perhaps via `getExternalFilesDirs()` (plural) and kin. Are you planning on using the Storage Access Framework to ask the user where to copy things to? If so, use Java I/O to copy from the `InputStream` from your source `Uri` to the `OutputStream` of your destination `Uri`. – CommonsWare Mar 15 '16 at 23:49
  • 1
    If i use the Java file system I don't have permission to modify the secondary sd card. example: create folder: (new File(path)).mkdir(); doesn't work, but utilizing the new SAF by documentFile.createDirectory(name); (where documentFile is created with DocumentFile.fromTreeUri(context, treeUri)) does work. So what I'm looking for is a way to copy files using using the DocumentsContract API. – Anonymous Mar 16 '16 at 01:40
  • 2
    As I noted, get a `Uri` for your original, get a `Uri` for your intended copy, open streams on both, and do the Java I/O. I don't recall a built-in copy or move operation, at least in the current shipping editions of Android. – CommonsWare Mar 16 '16 at 11:24
  • 1
    that worked very well, thank you! – Anonymous Mar 16 '16 at 20:35

1 Answers1

15

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;
}
Theo
  • 2,012
  • 1
  • 16
  • 29