ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
# 如何在 Java 中复制目录 > 原文: [https://howtodoinjava.com/java/io/how-to-copy-directories-in-java/](https://howtodoinjava.com/java/io/how-to-copy-directories-in-java/) 要将目录及其包含的所有子文件夹和文件从一个位置复制到另一个位置,请使用以下代码,该代码使用递归遍历目录结构,然后使用[`Files.copy()`](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#copy-java.nio.file.Path-java.nio.file.Path-java.nio.file.CopyOption...- "file copy")函数复制文件。 ## 目录复制示例源代码 在此示例中,我将`c:\temp`下的所有子目录和文件复制到新位置`c:\tempNew`。 ```java package com.howtodoinjava.examples.io; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; public class DirectoryCopyExample { public static void main(String[] args) throws IOException { //Source directory which you want to copy to new location File sourceFolder = new File("c:\\temp"); //Target directory where files should be copied File destinationFolder = new File("c:\\tempNew"); //Call Copy function copyFolder(sourceFolder, destinationFolder); } /** * This function recursively copy all the sub folder and files from sourceFolder to destinationFolder * */ private static void copyFolder(File sourceFolder, File destinationFolder) throws IOException { //Check if sourceFolder is a directory or file //If sourceFolder is file; then copy the file directly to new location if (sourceFolder.isDirectory()) { //Verify if destinationFolder is already present; If not then create it if (!destinationFolder.exists()) { destinationFolder.mkdir(); System.out.println("Directory created :: " + destinationFolder); } //Get all files from source directory String files[] = sourceFolder.list(); //Iterate over all files and copy them to destinationFolder one by one for (String file : files) { File srcFile = new File(sourceFolder, file); File destFile = new File(destinationFolder, file); //Recursive function call copyFolder(srcFile, destFile); } } else { //Copy the file content from one place to another Files.copy(sourceFolder.toPath(), destinationFolder.toPath(), StandardCopyOption.REPLACE_EXISTING); System.out.println("File copied :: " + destinationFolder); } } } Output: Directory created :: c:\tempNew File copied :: c:\tempNew\testcopied.txt File copied :: c:\tempNew\testoriginal.txt File copied :: c:\tempNew\testOut.txt ``` 使用`Files.copy()`方法,可以复制目录。 但是,目录内的文件不会被复制,因此即使原始目录包含文件,新目录也为空。 另外,如果目标文件存在,则复制将失败,除非指定了`REPLACE_EXISTING`选项。 验证是否正确复制了文件。 随意修改代码并以自己喜欢的方式使用它。 **祝您学习愉快!**