一、核心实现思路
- 校验源文件夹:确保源文件夹存在且是合法目录;
- 创建目标文件夹:若目标文件夹不存在,自动递归创建(包括多级父目录);
- 递归遍历源文件:遍历源文件夹下的所有文件/子目录,区分文件和目录分别处理;
- 复制文件:对文件使用字节流/通道复制,对目录递归创建并复制其内文件;
- 异常处理:捕获 IO 异常,保证复制过程的健壮性。
二、完整可运行代码
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
public class FolderCopyUtil {
public static void copyFolder(String sourceDirPath, String targetDirPath) throws IOException {
File sourceDir = new File(sourceDirPath);
File targetDir = new File(targetDirPath);
if (!sourceDir.exists()) {
throw new IOException("源文件夹不存在:" + sourceDirPath);
}
if (!sourceDir.isDirectory()) {
( + sourceDirPath);
}
(!targetDir.exists()) {
targetDir.mkdirs();
(!isCreated) {
( + targetDirPath);
}
}
File[] files = sourceDir.listFiles();
(files == ) {
;
}
(File file : files) {
targetDirPath + File.separator + file.getName();
(file.isFile()) {
copyFile(file, (targetFilePath));
System.out.println( + file.getPath() + + targetFilePath);
} (file.isDirectory()) {
copyFolder(file.getPath(), targetFilePath);
System.out.println( + file.getPath() + + targetFilePath);
}
}
}
IOException {
(targetFile.exists()) {
targetFile.delete();
(!isDeleted) {
( + targetFile.getPath());
}
}
( (sourceFile);
(targetFile);
fis.getChannel();
fos.getChannel()) {
;
inChannel.size();
(transferred < fileSize) {
transferred += inChannel.transferTo(transferred, fileSize - transferred, outChannel);
}
}
}
{
;
;
{
copyFolder(sourceDir, targetDir);
System.out.println();
} (IOException e) {
System.err.println( + e.getMessage());
e.printStackTrace();
}
}
}