import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CopyFiles {
// 存放文件的集合
private static Map<String, File> filePath = new ConcurrentHashMap<>();
// 创建含15个线程的线程池
private static ExecutorService eService = Executors.newFixedThreadPool(15);
public static void main(String[] args) {
System.out.println("==========开始扫描==========");
long startTime = System.currentTimeMillis(); // 记录开始时间
// 获取当前文件夹的绝对路径
String root = new File(CopyFiles.class.getResource("/").getPath()).getAbsolutePath();
// 首次扫描的文件路径
File rootPath = new File(root);
// 获取所有文件并且添加文件到文件集合
getFiles(rootPath);
System.out.println("==========扫描完成==========");
// 先创建copy文件夹
File copyDir = new File(root + "/copy/");
// 如果不存在就先创建copy文件夹
if (!copyDir.exists()) {
copyDir.mkdir();
}
System.out.println("==========开始复制文件==========");
// 遍历文件集合中的所有文件
filePath.forEach((name, file) -> {
// 复制文件的方法
eService.execute(() -> {
System.out.println("使用线程池中的 => " + Thread.currentThread().getName() + " 线程复制 => " + name);
// 获取流
try (FileInputStream is = new FileInputStream(file);
FileOutputStream os = new FileOutputStream(root + "/copy/" + name)) {
byte[] buf = new byte[1024 * 4];
int len = 0;
while ((len = is.read(buf)) != -1) {
os.write(buf, 0, len);
}
} catch (Exception e) {
throw new RuntimeException(e);
}
});
});
// 关闭线程池
eService.shutdown();
// 判断是否复制完成
for (;;) {
if (eService.isTerminated()) {
long endTime = System.currentTimeMillis(); // 记录结束时间
System.out.println("==========复制文件完成,总共耗时" + (endTime - startTime) + "ms==========");
break;
}
}
}
// 获取所有文件并且添加文件到文件集合
private static void getFiles(File rootPath) {
// 判断是不是一个文件夹
if (rootPath.isDirectory()) {
for (File file : rootPath.listFiles()) {
// 如果是个文件夹,就递归扫描
if (file.isDirectory()) {
// 用线程池中的线程扫描
eService.execute(() -> {
getFiles(file);
});
} else {
System.out.println("使用" + Thread.currentThread().getName() + "扫描到文件 => " + file.getName());
// 添加文件到文件集合
if (filePath.containsKey(file.getName())) { // 重名检测
System.out.println("==========检测到重复文件名" + file.getName() + ",自动拼接UUID==========");
filePath.put(file.getName() + "," + UUID.randomUUID().toString(), file);
} else {
filePath.put(file.getName(), file);
}
}
}
} else {
System.out.println("使用" + Thread.currentThread().getName() + "扫描到文件 => " + rootPath.getName());
// 添加文件到文件集合
if (filePath.containsKey(rootPath.getName())) { // 重名检测
System.out.println("==========检测到重复文件名" + rootPath.getName() + ",自动拼接UUID==========");
filePath.put(rootPath.getName() + "," + UUID.randomUUID().toString(), rootPath);
} else {
filePath.put(rootPath.getName(), rootPath);
}
}
}
}
Java移动当前文件夹下的所有文件夹下的文件到当前目录下的copy目录下
最新推荐文章于 2024-04-17 05:18:29 发布