当前位置: 移动技术网 > IT编程>开发语言>Java > java使用计算md5校验码方式比较两个文件是否相同

java使用计算md5校验码方式比较两个文件是否相同

2019年07月22日  | 移动技术网IT编程  | 我要评论

复制代码 代码如下:

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);
    }

}

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网