用到了apache的commons-codec-1.7.jar包, 用于比较文件的md5值
代码如下
public static boolean compareFolder(File file1, File file2) {
if (file1 == null || file2 == null) {
return false;
}
if (!file1.isDirectory() || !file2.isDirectory()) {
return false;
}
File[] listFiles1 = file1.listFiles();
File[] listFiles2 = file2.listFiles();
int fileCount1 = listFiles1.length;
int fileCount2 = listFiles2.length;
if (fileCount1 != fileCount2) {
return false;
}
for (int i = 0; i < fileCount1; i++) {
if (listFiles1[i].isFile() && listFiles2[i].isDirectory()) {
return false;
} else if (listFiles1[i].isDirectory() && listFiles2[i].isFile()) {
return false;
} else if (listFiles1[i].isFile() && listFiles2[i].isFile()) {
if (!compareFile(listFiles1[i], listFiles2[i])) {
return false;
}
} else if (listFiles1[i].isDirectory()
&& listFiles2[i].isDirectory()) {
if (!compareFolder(listFiles1[i], listFiles2[i])) {
return false;
}
}
}
return true;
}
public static boolean compareFile(File file1, File file2) {
if (file1 == null || file2 == null) {
return false;
}
if (!file1.isFile() || !file2.isFile()) {
return false;
}
try {
FileInputStream fis1 = new FileInputStream(file1);
FileInputStream fis2 = new FileInputStream(file2);
String md5Hex1 = DigestUtils.md5Hex(fis1);
String md5Hex2 = DigestUtils.md5Hex(fis2);
if (md5Hex1.equals(md5Hex2)) {
return true;
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return false;
}