帮助用户获取文件夹中的文件名,并将指定的文件从一个文件夹移动到另一个文件夹。
package cn.wenjianqianyi;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashSet;
import java.util.Set;
public class FileComparison {
public static void main(String[] args) {
// 定义三个文件夹路径
String folder1Path = "D:\\test\\test1";
String folder2Path = "D:\\test\\test2";
String folder3Path = "D:\\test\\test3";
// 获取文件夹1和文件夹2中的文件名
Set<String> filesInFolder1 = getFileNames(folder1Path);
Set<String> filesInFolder2 = getFileNames(folder2Path);
// 找出文件夹1中独有的文件
Set<String> uniqueFilesInFolder1 = new HashSet<>(filesInFolder1);
uniqueFilesInFolder1.removeAll(filesInFolder2);
// 找出文件夹2中独有的文件
Set<String> uniqueFilesInFolder2 = new HashSet<>(filesInFolder2);
uniqueFilesInFolder2.removeAll(filesInFolder1);
// 将独有文件剪切到文件夹3
moveFiles(uniqueFilesInFolder1, folder1Path, folder3Path);
moveFiles(uniqueFilesInFolder2, folder2Path, folder3Path);
System.out.println("文件剪切完成。");
}
private static Set<String> getFileNames(String folderPath) {
Set<String> fileNames = new HashSet<>();
//创建一个 File 对象 folder,表示传入的文件夹路径
File folder = new File(folderPath);
//调用 folder.listFiles() 方法获取文件夹中的所有文件和子文件夹,返回一个 File 数组
File[] files = folder.listFiles();
//检查 files 是否为 null,如果不为 null,则遍历 files 数组
//对于每个 File 对象 file,检查它是否是一个文件(file.isFile())
//如果是文件,则将其文件名(file.getName())添加到 fileNames 集合中
if (files != null) {
for (File file : files) {
if (file.isFile()) {
fileNames.add(file.getName());
}
}
}
return fileNames;
}
private static void moveFiles(Set<String> fileNames, String sourceFolderPath, String targetFolderPath) {
for (String fileName : fileNames) {
//使用 Paths.get 方法创建源文件路径 sourcePath 和目标文件路径 targetPath
Path sourcePath = Paths.get(sourceFolderPath, fileName);
Path targetPath = Paths.get(targetFolderPath, fileName);
try {
//尝试使用 Files.move 方法将文件从源路径移动到目标路径
Files.move(sourcePath, targetPath);
} catch (IOException e) {
//如果移动过程中发生 IOException,则捕获异常并打印堆栈跟踪
e.printStackTrace();
}
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.
- 54.
- 55.
- 56.
- 57.
- 58.
- 59.
- 60.
- 61.
- 62.
- 63.
- 64.
- 65.
- 66.
- 67.
- 68.
- 69.
- 70.
- 71.