java使用计算md5校验码方式比较两个文件是否相同
public class md5check {
/**
* 默认的密码字符串组合,用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合
*/
protected char hexdigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
protected messagedigest messagedigest = null;
{
try {
messagedigest = messagedigest.getinstance("md5");
} catch (nosuchalgorithmexception e) {
e.printstacktrace();
}
}
public string getfilemd5string(file file) throws ioexception {
inputstream fis;
fis = new fileinputstream(file);
byte[] buffer = new byte[1024];
int numread = 0;
while ((numread = fis.read(buffer)) > 0) {
messagedigest.update(buffer, 0, numread);
}
fis.close();
return buffertohex(messagedigest.digest());
}
public string getfilemd5string(inputstream in) throws ioexception {
byte[] buffer = new byte[1024];
int numread = 0;
while ((numread = in.read(buffer)) > 0) {
messagedigest.update(buffer, 0, numread);
}
in.close();
return buffertohex(messagedigest.digest());
}
private string buffertohex(byte bytes[]) {
return buffertohex(bytes, 0, bytes.length);
}
private string buffertohex(byte bytes[], int m, int n) {
stringbuffer stringbuffer = new stringbuffer(2 * n);
int k = m + n;
for (int l = m; l < k; l++) {
appendhexpair(bytes[l], stringbuffer);
}
return stringbuffer.tostring();
}
private void appendhexpair(byte bt, stringbuffer stringbuffer) {
char c0 = hexdigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换
// 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同
char c1 = hexdigits[bt & 0xf];// 取字节中低 4 位的数字转换
stringbuffer.append(c0);
stringbuffer.append(c1);
}
}
上一篇: Java List 用法实例详解