欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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

程序员文章站 2024-03-19 10:08:16
...
  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