java计算文件MD5值,比较两文件是否相同

比较两个文件是否相同,一般都是比较文件的MD5值是否相同,java中计算MD5值的方法如下:

    private MessageDigest mMessageDigest = null;
  
    try {
        mMessageDigest = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    
    /**
     * obtain the file's MD5
     */
    public String getFileMD5String(File file) {
        try {
            InputStream fis = new FileInputStream(file);
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = fis.read(buffer, 0, 1024)) > 0) {
                mMessageDigest.update(buffer, 0, length);
            }
            fis.close();
            return new BigInteger(1, mMessageDigest.digest()).toString(16);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


先利用MD5值比较文件之前,先判断文件大小是否一样,如果文件大小不一样,肯定不是相同文件

    private boolean isSmaeFile(String filePath1, String filePath2) {
        boolean result = true;

        File file1 = new File(filePath1);
        File file2 = new File (filePath2);

        if (externalFile.length() != internallFile.length()) {
            result = false;
            break;
        } else {
            String file1MD5 = getFileMD5String(file1);
            String file2MD5 = getFileMD5String(file2);
            if (file1MD5 != null && !file1MD5.equals(file2MD5)) {
                result = false;
                break;
            }
        }
        return result;
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值