版权声明:本文为博主原创文章,欢迎转载,转载请注明本文链接! https://blog.csdn.net/qq_38238041/article/details/83628934
package cn.bl.file;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 判断两个文件是否内容完全相同
* @author BarryLee
* @2018年11月1日@下午10:16:50
*/
public class FileEquals {
public static void main(String[] args) {
File file1 = new File("E:/a/a.txt");
File file2 = new File("E:/a/a - 副本.txt");
String str1 = getMD5Str(file1);
String str2 = getMD5Str(file2);
System.out.println(str1.equals(str2));
}
public static String getMD5Str(File file) {
if(!file.isFile()) {
System.out.println(file.getName()+"不是文件");
return null;
}
InputStream in = null;
try {
MessageDigest digest = MessageDigest.getInstance("MD5");
in = new FileInputStream(file);
byte[]bs = new byte[1024];
int len = -1;
while((len=in.read(bs))!=-1) {
digest.update(bs,0,len);
}
BigInteger bi = new BigInteger(1,digest.digest());
return bi.toString(16);
} catch (NoSuchAlgorithmException e) {
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
}