如何在 Java 中递归复制目录

x33g5p2x  于2021-10-16 转载在 Java  
字(0.7k)|赞(0)|评价(0)|浏览(328)

在本文中,您将学习如何将非空目录及其所有子目录和文件递归复制到 Java 中的另一个位置。

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);
                    }
                });
    }
}

相关文章

微信公众号

最新文章

更多