Java计算文件的SHA码和MD5码

 可参考:http://blog.csdn.net/hudashi/article/details/8394158

 1     /**
 2      * 计算文件的MD5码
 3      * @param file
 4      * @return
 5      */
 6     public static String getMD5(File file) {
 7         FileInputStream fis = null;
 8         try {
 9             MessageDigest md = MessageDigest.getInstance("MD5");
10             fis = new FileInputStream(file);
11             byte[] buffer = new byte[8192];
12             int length = -1;
13             System.out.println("开始算");
14             while ((length = fis.read(buffer)) != -1) {
15                 md.update(buffer, 0, length);
16             }
17             System.out.println("算完了");
18             return bytesToString(md.digest());
19         } catch (IOException ex) {
20             Logger.getLogger(MD5Util.class.getName()).log(Level.SEVERE, null, ex);
21             return null;
22         } catch (NoSuchAlgorithmException ex) {
23             Logger.getLogger(MD5Util.class.getName()).log(Level.SEVERE, null, ex);
24             return null;
25         } finally {
26             try {
27                 fis.close();
28             } catch (IOException ex) {
29                 Logger.getLogger(MD5Util.class.getName()).log(Level.SEVERE, null, ex);
30             }
31         }
32     }
33 
34     /**
35      * 得到文件的SHA码,用于校验
36      * @param file
37      * @return
38      */
39     public static String getSHA(File file) {
40         FileInputStream fis = null;
41         try {
42             MessageDigest md = MessageDigest.getInstance("SHA");
43             fis = new FileInputStream(file);
44             byte[] buffer = new byte[8192];
45             int length = -1;
46             System.out.println("开始算");
47             while ((length = fis.read(buffer)) != -1) {
48                 md.update(buffer, 0, length);
49             }
50             System.out.println("算完了");
51             return bytesToString(md.digest());
52         } catch (IOException ex) {
53             Logger.getLogger(MD5Util.class.getName()).log(Level.SEVERE, null, ex);
54             return null;
55         } catch (NoSuchAlgorithmException ex) {
56             Logger.getLogger(MD5Util.class.getName()).log(Level.SEVERE, null, ex);
57             return null;
58         } finally {
59             try {
60                 fis.close();
61             } catch (IOException ex) {
62                 Logger.getLogger(MD5Util.class.getName()).log(Level.SEVERE, null, ex);
63             }
64         }
65     }
66     

 

posted @ 2016-08-11 11:35  SummerChill  阅读(4946)  评论(0编辑  收藏  举报