FileMd5Util.java 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package com.fdkankan.fusion.common.util;
  2. import java.io.File;
  3. import java.io.FileInputStream;
  4. import java.security.MessageDigest;
  5. public class FileMd5Util {
  6. public static final String KEY_MD5 = "MD5";
  7. public static final String CHARSET_ISO88591 = "ISO-8859-1";
  8. public FileMd5Util() {
  9. }
  10. public static String getFileMD5(File file) {
  11. if (file.exists() && file.isFile()) {
  12. MessageDigest digest = null;
  13. FileInputStream in = null;
  14. byte[] buffer = new byte[1024];
  15. try {
  16. digest = MessageDigest.getInstance("MD5");
  17. in = new FileInputStream(file);
  18. while(true) {
  19. int len;
  20. if ((len = in.read(buffer, 0, 1024)) == -1) {
  21. in.close();
  22. break;
  23. }
  24. digest.update(buffer, 0, len);
  25. }
  26. } catch (Exception var9) {
  27. var9.printStackTrace();
  28. return null;
  29. }
  30. byte[] by = digest.digest();
  31. StringBuffer sbf = new StringBuffer();
  32. for(int j = 0; j < by.length; ++j) {
  33. int i = by[j];
  34. if (i < 0) {
  35. i += 256;
  36. } else if (i < 16) {
  37. sbf.append("0");
  38. }
  39. sbf.append(Integer.toHexString(i));
  40. }
  41. return sbf.toString();
  42. } else {
  43. return null;
  44. }
  45. }
  46. public static String getFileMD5(String filepath) {
  47. File file = new File(filepath);
  48. return getFileMD5(file);
  49. }
  50. public static byte[] encryptMD5(byte[] data) throws Exception {
  51. MessageDigest md5 = MessageDigest.getInstance("MD5");
  52. md5.update(data);
  53. return md5.digest();
  54. }
  55. public static byte[] encryptMD5(String data) throws Exception {
  56. return encryptMD5(data.getBytes("ISO-8859-1"));
  57. }
  58. public static boolean isSameMd5(File file1, File file2) {
  59. String md5_1 = getFileMD5(file1);
  60. String md5_2 = getFileMD5(file2);
  61. return md5_1.equals(md5_2);
  62. }
  63. public static boolean isSameMd5(String filepath1, String filepath2) {
  64. File file1 = new File(filepath1);
  65. File file2 = new File(filepath2);
  66. return isSameMd5(file1, file2);
  67. }
  68. public static void main(String[] args) {
  69. System.out.println("obj1: " + getFileMD5(new File("F:\\桌面\\c11m-T11-EA\\log\\i6VhiQ2Q-copy.obj")));
  70. System.out.println("obj: " + getFileMD5(new File("F:\\桌面\\c11m-T11-EA\\log\\i6VhiQ2Q.obj")));
  71. }
  72. }