Java取文件MD5值
public static String getFileMD5(String path) {
BigInteger bi = null;
try {
byte[] buffer = new byte[8192];
int len = 0;
MessageDigest md = MessageDigest.getInstance("MD5");
File f = new File(path);
FileInputStream fis = new FileInputStream(f);
while ((len = fis.read(buffer)) != -1) {
md.update(buffer, 0, len);
}
fis.close();
byte[] b = md.digest();
bi = new BigInteger(1, b);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return bi.toString(16);
}
public static String getStringMD5(String input) {
String result = "";
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(input.getBytes());
byte b[] = md.digest();
int i;
StringBuffer buf = new StringBuffer("");
for (int offset = 0; offset < b.length; offset++) {
i = b[offset];
if (i < 0)
i += 256;
if (i < 16)
buf.append("0");
buf.append(Integer.toHexString(i));
}
result = buf.toString();
} catch (NoSuchAlgorithmException e) {
System.out.println(e);
}
return result;
}
测试方法
public static void main(String[] args) {
long beginTime = System.currentTimeMillis();
String md5 = getFileMD5("D:\\w.jpg");
System.out.println("字符的MD5:"+getStringMD5("hello"));
long endTime = System.currentTimeMillis();
System.out.println("MD5:" + md5 + "\n 耗时:" + ((endTime - beginTime) / 1000) + "s");
}