使用MD5算法计算文件MD5值

前期准备:
需要Apache Commons Codec
maven 导入:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>

啥都不多数, 代码送上

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
 
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
 
/**
 *MD5文件计算工具
 */
public class MD5FileUtils{
    /**
     * 获取一个文件的md5值(可处理大文件)
     * @return md5 value
     */
    public static String getMD5(File file) {
        FileInputStream fileInputStream = null;
        try {
            MessageDigest MD5 = MessageDigest.getInstance("MD5");
            fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                MD5.update(buffer, 0, length);
            }
            return new String(Hex.encodeHex(MD5.digest()));
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null){
                    fileInputStream.close();
                    }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
    /**
     * 求一个字符串的md5值
     * @param target 字符串
     * @return md5 value
     */
    public static String MD5(String target) {
        return DigestUtils.md5Hex(target);
    }
 
    public static void main(String[] args) {
    	//测试
        long beginTime = System.currentTimeMillis();
        File file = new File("C:/Users/Miao/Downloads/apache-tomcat-8.5.61-windows-x64.zip");
        String md5 = getMD5(file);
        long endTime = System.currentTimeMillis();
        System.out.println("MD5:" + md5 + "\n 耗时:" + ((endTime - beginTime) / 1000) + "s");
    }
}

输出结果如下:

MD5:fc052ff86a2db1ef67ff5765bfd82c19
耗时:0s
如有帮助, 可以支持一下
分享到:

发表评论

昵称

沙发空缺中,还不快抢~