MD5 检查文件一致性

 1 package test;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.math.BigInteger;
 6 import java.security.MessageDigest;
 7 import java.util.HashMap;
 8 import java.util.Map;
 9 
10 public class FileDigest {
11     /**
12      * 获取单个文件的MD5值!
13      * 
14      * @param file
15      * @return
16      */
17     public static String getFileMD5(File file) {
18         if (!file.isFile()) {
19             return null;
20         }
21         MessageDigest digest = null;
22         FileInputStream in = null;
23         byte buffer[] = new byte[1024];
24         int len;
25         try {
26             digest = MessageDigest.getInstance("MD5");
27             in = new FileInputStream(file);
28             while ((len = in.read(buffer, 0, 1024)) != -1) {
29                 digest.update(buffer, 0, len);
30             }
31             in.close();
32         } catch (Exception e) {
33             e.printStackTrace();
34             return null;
35         }
36         BigInteger bigInt = new BigInteger(1, digest.digest());
37         return bigInt.toString(16);
38     }
39 
40     /**
41      * 获取文件夹中文件的MD5值
42      * 
43      * @param file
44      * @param listChild
45      *            ;true递归子目录中的文件
46      * @return
47      */
48     public static Map<String, String> getDirMD5(File file, boolean listChild) {
49         if (!file.isDirectory()) {
50             return null;
51         }
52         // <filepath,md5>
53         Map<String, String> map = new HashMap<String, String>();
54         String md5;
55         File files[] = file.listFiles();
56         for (int i = 0; i < files.length; i++) {
57             File f = files[i];
58             if (f.isDirectory() && listChild) {
59                 map.putAll(getDirMD5(f, listChild));
60             } else {
61                 md5 = getFileMD5(f);
62                 if (md5 != null) {
63                     map.put(f.getPath(), md5);
64                 }
65             }
66         }
67         return map;
68     }
69 
70     public static void main(String[] args) {
71         File file1 = new File("H:/update/lib/111.txt");
72         File file2 = new File("H:/1111.txt");
73         System.out.println(getFileMD5(file1).equals(getFileMD5(file2)));
74     }
75 
76 }
posted @ 2012-11-20 15:52  雲端之風  阅读(2098)  评论(0编辑  收藏  举报