import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Test {
static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
public static String getMD5Encrypt(String filePath) {
FileInputStream input = null;
try {
MessageDigest md = MessageDigest.getInstance("MD5");
input = new FileInputStream(filePath);
byte[] buffer = new byte[2048];
int length = -1;
while ((length = input.read(buffer)) != -1) {
md.update(buffer, 0, length);
}
byte[] b = md.digest();
return byteToHexString(b);
} catch (NoSuchAlgorithmException | IOException e) {
e.printStackTrace();
return null;
} finally {
try {
if (input != null)
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private static String byteToHexString(byte[] b) {
char[] str = new char[16 * 2];
int k = 0;
for (int i = 0; i < 16; i++) {
byte byte0 = b[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
public static void main(String[] args) {
String md5Encrypt = getMD5Encrypt("D:\\开发测试.zip");
System.out.println(md5Encrypt);
if ("e65b0af695b7a875d34bcce25453e7bd".equals(md5Encrypt))
System.out.println("文件内容一致");
}
}