java如何复制文件夹及文件
Java 复制文件夹及文件的方法
Java 提供了多种方式实现文件夹及文件的复制操作,以下是几种常见的方法:
使用 Files.copy() 方法(Java 7+)
适用于简单文件复制,支持 NIO(非阻塞 I/O)操作:
Path sourcePath = Paths.get("source/file.txt");
Path targetPath = Paths.get("target/file.txt");
Files.copy(sourcePath, targetPath, StandardCopyOption.REPLACE_EXISTING);
对于目录复制需要递归处理:

public static void copyFolder(Path source, Path target) throws IOException {
Files.walk(source).forEach(from -> {
Path to = target.resolve(source.relativize(from));
try {
Files.copy(from, to, StandardCopyOption.REPLACE_EXISTISTING);
} catch (IOException e) {
e.printStackTrace();
}
});
}
使用传统 IO 流方式
适用于所有 Java 版本的文件复制:
public static void copyFile(File source, File dest) throws IOException {
try (InputStream is = new FileInputStream(source);
OutputStream os = new FileOutputStream(dest)) {
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
}
}
目录复制需要递归处理:

public static void copyDirectory(File sourceDir, File destDir) throws IOException {
if (!destDir.exists()) {
destDir.mkdir();
}
for (File file : sourceDir.listFiles()) {
if (file.isDirectory()) {
copyDirectory(file, new File(destDir, file.getName()));
} else {
copyFile(file, new File(destDir, file.getName()));
}
}
}
使用 Apache Commons IO 库
简化操作,适合复杂场景:
// 单文件复制
FileUtils.copyFile(srcFile, destFile);
// 目录复制
FileUtils.copyDirectory(srcDir, destDir);
需要添加依赖:
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.11.0</version>
</dependency>
注意事项
- 目标目录需要先创建
- 大文件建议使用缓冲流
- 注意处理文件权限问题
- 考虑使用多线程提升大批量文件复制效率
以上方法可根据具体需求选择,NIO 方式性能较好,传统 IO 兼容性更广,第三方库则提供了更简洁的 API。






