java如何复制文件夹及文件
使用 Files.copy 方法(Java NIO)
Java NIO 的 Files.copy 方法适合复制单个文件或空文件夹。对于非空文件夹,需递归处理子目录和文件。
import java.nio.file.*;
public static void copyFolder(Path source, Path target) throws IOException {
Files.walk(source).forEach(srcPath -> {
try {
Path destPath = target.resolve(source.relativize(srcPath));
Files.copy(srcPath, destPath, StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
e.printStackTrace();
}
});
}
使用 Apache Commons IO 库
Apache Commons IO 的 FileUtils.copyDirectory 方法提供了更简洁的解决方案,需添加依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
代码示例:
import org.apache.commons.io.FileUtils;
FileUtils.copyDirectory(new File("sourcePath"), new File("targetPath"));
递归手动实现
若需不依赖第三方库,可手动实现递归复制:
import java.io.*;
public static void copyFolder(File source, File target) throws IOException {
if (source.isDirectory()) {
if (!target.exists()) target.mkdir();
for (String file : source.list()) {
copyFolder(new File(source, file), new File(target, file));
}
} else {
try (InputStream in = new FileInputStream(source);
OutputStream out = new FileOutputStream(target)) {
byte[] buffer = new byte[1024];
int length;
while ((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
}
}
}
注意事项
- 目标文件夹需有写入权限。
- 大文件建议使用缓冲流(如
BufferedInputStream)。 - 符号链接需特殊处理,避免无限递归。
- Java 7+ 推荐 NIO 方式,性能更优。







