Java计算文件MD5值(支持大文件)

 

Java计算文件MD5值(支持大文件)


  1. package com.hthl.xxtd;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileInputStream;  
  5. import java.io.IOException;  
  6. import java.security.MessageDigest;  
  7.   
  8. import org.apache.commons.codec.binary.Hex;  
  9. import org.apache.commons.codec.digest.DigestUtils;  
  10.   
  11. /** 
  12.  *MD5计算工具 xuxile 2017-09-13 
  13.  */  
  14. public class Md5CaculateUtil {  
  15.   
  16.     /** 
  17.      * 获取一个文件的md5值(可处理大文件) 
  18.      * @return md5 value 
  19.      */  
  20.     public static String getMD5(File file) {  
  21.         FileInputStream fileInputStream = null;  
  22.         try {  
  23.             MessageDigest MD5 = MessageDigest.getInstance("MD5");  
  24.             fileInputStream = new FileInputStream(file);  
  25.             byte[] buffer = new byte[8192];  
  26.             int length;  
  27.             while ((length = fileInputStream.read(buffer)) != -1) {  
  28.                 MD5.update(buffer, 0, length);  
  29.             }  
  30.             return new String(Hex.encodeHex(MD5.digest()));  
  31.         } catch (Exception e) {  
  32.             e.printStackTrace();  
  33.             return null;  
  34.         } finally {  
  35.             try {  
  36.                 if (fileInputStream != null){  
  37.                     fileInputStream.close();  
  38.                     }  
  39.             } catch (IOException e) {  
  40.                 e.printStackTrace();  
  41.             }  
  42.         }  
  43.     }  
  44.   
  45.     /** 
  46.      * 求一个字符串的md5值 
  47.      * @param target 字符串 
  48.      * @return md5 value 
  49.      */  
  50.     public static String MD5(String target) {  
  51.         return DigestUtils.md5Hex(target);  
  52.     }  
  53.   
  54.     public static void main(String[] args) {  
  55.         long beginTime = System.currentTimeMillis();  
  56.         File file = new File("D:/1/pdi-ce-7.0.0.0-24.zip");  
  57.         String md5 = getMD5(file);  
  58.         long endTime = System.currentTimeMillis();  
  59.         System.out.println("MD5:" + md5 + "\n 耗时:" + ((endTime - beginTime) / 1000) + "s");  
  60.     }  
  61. }  



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值