在本文中,您将学习如何将非空目录及其所有子目录和文件递归复制到 Java 中的另一个位置。
import java.io.IOException;
import java.nio.file.*;
public class CopyDirectoryRecursively {
public static void main(String[] args) throws IOException {
Path sourceDir = Paths.get( "/Users/callicoder/Desktop/new-media");
Path destinationDir = Paths.get("/Users/callicoder/Desktop/media");
// Traverse the file tree and copy each file/directory.
Files.walk(sourceDir)
.forEach(sourcePath -> {
try {
Path targetPath = destinationDir.resolve(sourceDir.relativize(sourcePath));
System.out.printf("Copying %s to %s%n", sourcePath, targetPath);
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException ex) {
System.out.format("I/O error: %s%n", ex);
}
});
}
}
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://www.callicoder.com/java-copy-directory-recursively/
内容来源于网络,如有侵权,请联系作者删除!