我有一个例程,我已经使用了一段时间来将目录从 SD 卡复制到插入的 USB 驱动器。它可以工作,但由于可以有 3000 张照片,我相信你会觉得它有点慢。所以我正在尝试实现某种更新进度条。
这是我的复制代码;
public void copyDirectory(File sourceLocation , File targetLocation)
throws IOException {
Log.e("Backup", "Starting backup");
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 {
Log.e("Backup", "Creating backup directory");
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);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
Log.e("Backup", "Finished");
}
}
我假设我需要在开始之前检查目录有多大,所以我添加了:
public static int CountFilesInDirectory(String location) {
File f = new File(location);
int count = 0;
for (File file : f.listFiles()) {
if (file.isFile()) {
count++;
}
}
return count;
}
但我想,我无法弄清楚如何将 A 和 B 放在一起。我不知道如何在正确的位置增加更新。- 我可能走错了路!任何提示真的将不胜感激。