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


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


转自:https://blog.csdn.net/xuxile/article/details/77963894


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值