我正在创建一个递归函数,该函数允许我复制目录的内容,包括子目录及其内容。我编写的函数似乎复制了所有内容,但我似乎仍然在控制台中收到错误,提示 java.nio.file.FileAlreadyExistsException: C:\Users\Vinny\Desktop esting estfolder2。
我的源文件夹名为
testfolder
,我要复制到的文件夹名为 testing
。
源文件夹文件内容如下:
非常简单的文件夹/文件。
我的递归代码是这样的:(请注意,我的代码尚未清理)
public void copyFiles(File src, Files dst) throws IOException {
// We will start by listing all subdirectories and files
String[] files = src.list();
// Loop through each file / directory
for (int i = 0; i < files.length; i++) {
// Check if the file is a directory
if (new File(src + "\\" + files[i]).isDirectory()) {
// We have a directory, so we will make sure the dst folder has the same sub folders
if (Files.notExists(new File(dst + "\\" + files[i]).toPath(), LinkOption.NOFOLLOW_LINKS)) {
// If directory does not exist, we shall create it
new File(dst + "\\" + files[i]).mkdir();
}
// Go into that subdirectory and copy all its contents as well
copyFiles(new File(src + "\\" + files[i]), new File(dst + "\\" + files[i]));
}
// Copy the files
Files.copy(new File(src + "\\" + files[i]).toPath(), new File(dst + "\\" + files[i]).toPath());
}
}
当目标不存在时,
Files.copy()
调用适用于目录。你错过了“其他”。复制目录树后,您可以继续前往 Files.copy
文件夹 src -> dest。
else
// Copy the files
Files.copy(new File(src + "\\" + files[i]).toPath(), new File(dst + "\\" + files[i]).toPath());
除了混合
File
+Path
+Files
,您还可以使用 Files.find
: 执行递归复制到新目标
public static void copy(Path src, Path dest) throws IOException {
try(var stream = Files.find(src, Integer.MAX_VALUE, (p,a) -> true /* or other condition */)) {
stream.forEach(p -> copyItem(p, dest.resolve(src.relativize(p))));
}
}
private static Path copyItem(Path p, Path target) {
// System.out.println("Files.copy("+p + ", "+target+")");
try {
// Drop REPLACE_EXISTING here if want existing files to be preserved
Files.copy(p, target, StandardCopyOption.REPLACE_EXISTING, StandardCopyOption.COPY_ATTRIBUTES);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return target;
}
因此,在使用 eclipse java 调试器之后,我意识到在创建目录后,它在执行 Files.copy 时也会尝试复制它。在检查它是否是目录时,我只需将 Files.copy 放入 else 语句中即可。