java计算文件32位md5值

 1 protected static String getFileMD5(String fileName)
 2     {
 3         File file = new File(fileName);
 4         if(!file.exists() || !file.isFile()){
 5             return "";
 6         }
 7         
 8         byte[] buffer = new byte[2048];
 9         try {
10             MessageDigest digest = MessageDigest.getInstance("MD5");
11             FileInputStream in = new FileInputStream(file);
12             while(true){
13                 int len = in.read(buffer,0,2048);
14                 if(len != -1){
15                     digest.update(buffer, 0, len);
16                 }else{
17                     break;
18                 }
19             }
20             in.close();
21             
22             byte[] md5Bytes  = digest.digest();
23             StringBuffer hexValue = new StringBuffer();
24             for (int i = 0; i < md5Bytes.length; i++) {
25                 int val = ((int) md5Bytes[i]) & 0xff;
26                 if (val < 16) {
27                     hexValue.append("0");
28                 }
29                 hexValue.append(Integer.toHexString(val));
30             }
31             return hexValue.toString();
32             
33             //String hash = new BigInteger(1,digest.digest()).toString(16);
34             //return hash;
35             
36         } catch (NoSuchAlgorithmException e) {
37             // TODO Auto-generated catch block
38             e.printStackTrace();
39             return "";
40         } catch (FileNotFoundException e) {
41             // TODO Auto-generated catch block
42             e.printStackTrace();
43             return "";
44         } catch (IOException e) {
45             // TODO Auto-generated catch block
46             e.printStackTrace();
47             return "";
48         }
49     }

how to use:

1 String file = "d://one.zip";
2 String md5 = getFileMD5(file);

 

posted @ 2016-04-05 14:07  VZXM  阅读(2063)  评论(0编辑  收藏  举报