MD5Util校验大型文件

 1 import java.io.File;
2 import java.io.FileInputStream;
3 import java.io.IOException;
4 import java.security.MessageDigest;
5 import java.security.NoSuchAlgorithmException;
6 import org.springframework.stereotype.Component;
7 import com.tg.exception.DataValidException;
8
9 @Component
10 public class MD5Util implements IMD5Util {
11 /**
12 * 默认的密码字符串组合,apache校验下载的文件的正确性用的就是默认的这个组合
13 */
14 protected static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
15 protected static MessageDigest messageDigest = null;
16 static {
17 try {
18 messageDigest = MessageDigest.getInstance("MD5");
19 } catch (NoSuchAlgorithmException e) {
20 System.err.println(MD5Util.class.getName() + "初始化失败,MessageDigest不支持MD5Util.");
21 e.printStackTrace();
22 }
23 }
24
25 /**
26 * 计算文件的MD5
27 *
28 * @param fileName
29 * 文件的绝对路径
30 * @return
31 * @throws IOException
32 */
33 public String getFileMD5String(String fileName) throws IOException {
34 File f = new File(fileName);
35 return getFileMD5String(f);
36 }
37
38 /**
39 * 计算文件的MD5,重载方法
40 *
41 * @param file
42 * 文件对象
43 * @return
44 * @throws IOException
45 */
46 public String getFileMD5String(File file) throws IOException {
47 if (!file.exists() || !file.isFile()) {
48 throw new DataValidException("不是有效文件!");
49 }
50 FileInputStream in = new FileInputStream(file);
51 byte[] buffer = new byte[1024 * 1024 * 10];
52 int len = 0;
53 while ((len = in.read(buffer)) > 0) {
54 messageDigest.update(buffer, 0, len);
55 }
56 in.close();
57 return bufferToHex(messageDigest.digest());
58 }
59
60 private String bufferToHex(byte bytes[]) {
61 return bufferToHex(bytes, 0, bytes.length);
62 }
63
64 private String bufferToHex(byte bytes[], int m, int n) {
65 StringBuffer stringbuffer = new StringBuffer(2 * n);
66 int k = m + n;
67 for (int l = m; l < k; l++) {
68 appendHexPair(bytes[l], stringbuffer);
69 }
70 System.out.println("文件MD5值:" + stringbuffer);
71 return stringbuffer.toString();
72 }
73
74 private void appendHexPair(byte bt, StringBuffer stringbuffer) {
75 char c0 = hexDigits[(bt & 0xf0) >> 4];
76 char c1 = hexDigits[bt & 0xf];
77 stringbuffer.append(c0);
78 stringbuffer.append(c1);
79 }
80 }

本例参考自http://zhouzaibao.iteye.com/blog/343870与http://hi.baidu.com/chenxiaowen/blog/item/9a9cb6deb5c2e95dccbf1abe.html

你可能感兴趣的:(util)