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

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/yin1031468524/article/details/78294607

比较两个文件是否相同,一般都是比较文件的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;
    }

猜你喜欢

转载自blog.csdn.net/yin1031468524/article/details/78294607