将文件从 SD 卡的文件夹复制到 SD 卡的另一个文件夹 [英] Copy files from a folder of SD card into another folder of SD card
本文介绍了将文件从 SD 卡的文件夹复制到 SD 卡的另一个文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否可以以编程方式将 sdcard 中存在的文件夹复制到另一个存在相同 sdcard 的文件夹中??
Is it possible to copy a folder present in sdcard to another folder present the same sdcard programmatically ??
如果是这样,该怎么做?
If so, how to do that?
推荐答案
该示例的改进版本:
// If targetLocation does not exist, it will be created.
public void copyDirectory(File sourceLocation , File targetLocation)
throws IOException {
if (sourceLocation.isDirectory()) {
if (!targetLocation.exists() && !targetLocation.mkdirs()) {
throw new IOException("Cannot create dir " + targetLocation.getAbsolutePath());
}
String[] children = sourceLocation.list();
for (int i=0; i<children.length; i++) {
copyDirectory(new File(sourceLocation, children[i]),
new File(targetLocation, children[i]));
}
} else {
// make sure the directory we plan to store the recording in exists
File directory = targetLocation.getParentFile();
if (directory != null && !directory.exists() && !directory.mkdirs()) {
throw new IOException("Cannot create dir " + directory.getAbsolutePath());
}
InputStream in = new FileInputStream(sourceLocation);
OutputStream out = new FileOutputStream(targetLocation);
// Copy the bits from instream to outstream
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
}
}
如果传递的目标文件位于不存在的目录中,则有一些更好的错误处理和更好的处理.
Got some better error handling and better handles if the passed target file lies in a directory that does not exist.
这篇关于将文件从 SD 卡的文件夹复制到 SD 卡的另一个文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文