我正在实现一个文件浏览器功能的应用程序。我知道如何使用ACTION_OPEN_DOCUMENT_TREE意图获得外部SD卡的持久权限,并且知道如何使用DocumentFile类创建文件夹和删除文件/文件夹。
但是,我无法找到一种将文件复制/移动到外部SD卡文件夹的方法。你能指导我正确的方向吗?
但是,我无法找到一种将文件复制/移动到外部SD卡文件夹的方法。你能指导我正确的方向吗?
我已经通过 Stack Overflow 上的许多示例找到了解决方案。我的音乐文件解决方案:
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;
}
getExternalFilesDirs()
(复数)等方式,您无法访问“外部SD卡文件夹”。您是否计划使用存储访问框架来询问用户要将东西复制到哪里?如果是这样,请使用Java I/O从源Uri
的InputStream
复制到目标Uri
的OutputStream
。 - CommonsWareUri
,获取拟复制文件的Uri
,在两个文件上打开流,并进行Java I/O操作。 我不记得Android当前发布版本中是否有内置的复制或移动操作。 - CommonsWare