package com.nstc.aims.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.StandardCopyOption;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.io.File;
import java.io.IOException;
/**
*使用DFS 算法在Java 中复制文件夹的实现 */
public class FolderCopy {
private static int step = 1;
public static void main(String[] args) throws IOException {
String sourceFolder = "path/to/source/folder";
String destinationFolder = "path/to/destination/folder";
copyFolder(new File(sourceFolder), new File(destinationFolder));
}
public static void copyFolder(File sourceFolder, File destinationFolder) throws IOException {
print("sourceFolder="+sourceFolder.getAbsolutePath());
print("destinationFolder="+destinationFolder.getAbsolutePath());
//如果源文件夹不存在,则无法复制它 if (!sourceFolder.exists()) {
return;
}
//如果目标文件夹不存在,创建它 if (!destinationFolder.exists()) {
print(true, "目标文件夹不存在,创建:["+destinationFolder.getAbsolutePath()+"]");
destinationFolder.mkdirs();
}
//遍历源文件夹中的所有文件和子文件夹 for (File file : sourceFolder.listFiles()) {
if (file.isDirectory()) {
print(true, "当前文件是文件夹:["+file.getAbsolutePath()+"]");
//如果当前文件是文件夹,则递归调用此函数以复制该文件夹及其内容 String newSourceFolderPath = file.getAbsolutePath();
String newDestinationFolderPath = newSourceFolderPath.replace(sourceFolder.getAbsolutePath(), destinationFolder.getAbsolutePath());
File newSourceFolder = new File(newSourceFolderPath);
File newDestinationFolder = new File(newDestinationFolderPath);
copyFolder(newSourceFolder, newDestinationFolder);
} else {
//如果当前文件是文件,则复制该文件到目标文件夹中 String newFilePath = file.getAbsolutePath().replace(sourceFolder.getAbsolutePath(), destinationFolder.getAbsolutePath());
File newFile = new File(newFilePath);
print(true,"当前文件不是文件夹:["+file.getAbsolutePath()+"]==> 复制到目标文件中:["+newFile.getAbsolutePath()+"]");
java.nio.file.Files.copy(file.toPath(), newFile.toPath(), StandardCopyOption.REPLACE_EXISTING);
}
}
}
private static void print(boolean printStep, String info){
if(printStep) {
System.out.println("========step=" + step++);
}
System.out.println(info);
}
private static void print(String info){
print(false, info);
}
}
使用DFS算法在Java中复制文件夹的实现 原创
没有更多推荐了 [去首页]