今天备份文件到光盘上,发现不同时间的文件中有许多重复的文件,因此想到写一段代码来删除这些重复的文件。
前提条件是:
1、有二个目录,一个是已经备份过的,设其名字是sourceDir,一个是将要备份的targetDir
2、要求:将后者目录中所有与前者目录中重复的文件删除。因此前者中的文件不变,后者中只保留了与前者不同的文件,相同的都被删除
3、相同的判断依据是:相同文件名、相同大小,以及相同的修改日期,三个条件全部满足者视为相同。
思路是:
1、读取sourceDir中的所有文件信息
2、对targetDir中的每个文件,与前一步中的信息比对,如果相同,立即删除
代码如下:
package deleteDuplicateFile;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
public class deleteDuplicateFile {
private static Map<String, String> fileInfo = new HashMap<String, String>();
private static int count = 0;
private static long size = 0;
private static int countDel = 0;
private static long sizeDel = 0;
// 原始的文件
private static String sourceDir = "E:/___Data/_RawData/数码照片/HNG/数码照片-(010)-2003-2015-倪铮";
// 需要删除的文件, 如果有重复的,就会被删除
private static String targetDir = "E:/___Data/_RawData/数码照片/NZ";
// 只显示
private static boolean showOnly = true;
public static void main(String[] args) {
if (sourceDir.equals(targetDir)) {
// 二者相同时, 会删除所有相同的文件, 绝对不能允许
System.out.println("The dir are same. Exit.");
System.exit(0);
}
saveSourceDir(new File(sourceDir));
if (targetDir != null && targetDir.trim().length() > 0) {
delSourceDir(new File(targetDir));
}
System.out.println("There are " + count + " pair of duplicate files. The size is " + size);
System.out.println("=============================");
System.out.println("There are " + countDel + " files deleted. The size is " + sizeDel);
System.out.println("=============================");
}
private static void saveSourceDir(File dir) { // 递归列出目录和文件
if (dir.isFile()) {
String path = dir.getPath();
String infor = dir.getName() + "-" + dir.length() + "-" + dir.lastModified();
if (fileInfo.keySet().contains(infor)) {
count++;
size += dir.length();
System.out.println("[1]" + path);
System.out.println("[2]" + fileInfo.get(infor));
System.out.println();
} else {
fileInfo.put(infor, path);
}
} else {
String[] children = dir.list();
if (children != null) {
for (int i = 0; i < children.length; i++) {
saveSourceDir(new File(dir, children[i])); // 直接递归调用
}
}
}
}
private static void delSourceDir(File dir) { // 递归列出目录和文件
if (dir.isFile()) {
String path = dir.getPath();
String infor = dir.getName() + "-" + dir.length() + "-" + dir.lastModified();
if (fileInfo.keySet().contains(infor)) {
countDel++;
sizeDel += dir.length();
if(showOnly){
System.out.println("[1]" + path + ". Not delete");
}else{
System.out.println("[D]" + path);
dir.delete();
}
}
} else {
String[] children = dir.list();
if (children != null) {
for (int i = 0; i < children.length; i++) {
delSourceDir(new File(dir, children[i])); // 直接递归调用
}
}
}
}
}