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 ?
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With