JAVA 生成文件的MD5码

下面的代码是自己写的:

Java代码   收藏代码
  1. /** 
  2.  * Copyright 2012 
  3.  * 
  4.  * All right reserved 
  5.  *  
  6.  * Created on 2012-8-31下午5:43:58 
  7.  */  
  8. package com.test.md5;  
  9.   
  10. import java.io.File;  
  11. import java.io.FileInputStream;  
  12. import java.io.FileNotFoundException;  
  13. import java.io.IOException;  
  14. import java.io.InputStream;  
  15. import java.security.MessageDigest;  
  16. import java.security.NoSuchAlgorithmException;  
  17.   
  18. import org.apache.log4j.Logger;  
  19.   
  20. /** 
  21.  *  
  22.  * @author xuepeng 
  23.  *  
  24.  */  
  25. public class MD5Checksum {  
  26.     private static Logger LOGGER = Logger.getLogger(MD5Checksum.class);  
  27.   
  28.     private static byte[] createChecksum(String filename) {  
  29.         InputStream fis = null;  
  30.         try {  
  31.             fis = new FileInputStream(filename);  
  32.             byte[] buffer = new byte[1024];  
  33.             MessageDigest complete = MessageDigest.getInstance("MD5");  
  34.             int numRead = -1;  
  35.   
  36.             while ((numRead = fis.read(buffer)) != -1) {  
  37.                 complete.update(buffer, 0, numRead);  
  38.             }  
  39.             return complete.digest();  
  40.         } catch (FileNotFoundException e) {  
  41.             LOGGER.error(e.getMessage(), e);  
  42.         } catch (NoSuchAlgorithmException e) {  
  43.             LOGGER.error(e.getMessage(), e);  
  44.         } catch (IOException e) {  
  45.             LOGGER.error(e.getMessage(), e);  
  46.         } finally {  
  47.             try {  
  48.                 if (null != fis) {  
  49.                     fis.close();  
  50.                 }  
  51.             } catch (IOException e) {  
  52.                 LOGGER.error(e.getMessage(), e);  
  53.             }  
  54.         }  
  55.         return null;  
  56.   
  57.     }  
  58.   
  59.     // see this How-to for a faster way to convert  
  60.     // a byte array to a HEX string  
  61.     public static String getMD5Checksum(String filename) {  
  62.       
  63.             if (!new File(filename).isFile()) {  
  64.                 LOGGER.error("Error: " + filename  
  65.                         + " is not a valid file.");  
  66.                 return null;  
  67.             }  
  68.             byte[] b = createChecksum(filename);  
  69.             if(null == b){  
  70.                 LOGGER.error("Error:create md5 string failure!");  
  71.                 return null;  
  72.             }  
  73.             StringBuilder result = new StringBuilder();  
  74.   
  75.             for (int i = 0; i < b.length; i++) {  
  76.                 result.append(Integer.toString((b[i] & 0xff) + 0x10016)  
  77.                         .substring(1));  
  78.             }  
  79.             return result.toString();  
  80.   
  81.     }  
  82.   
  83.     public static void main(String args[]) {  
  84.         try {  
  85.             long beforeTime = System.currentTimeMillis();  
  86.             String path = "C:\\Users\\user\\Desktop\\work_shedule.txt";  
  87.             String before = "999E42920C54CF7D66190731CD54F0E6".toLowerCase();  
  88.             String md5 = getMD5Checksum(path);  
  89.             System.out.println(md5);  
  90.             System.out.println(md5.equals(before));  
  91.               
  92.             File file = new File(path);  
  93.               
  94.             System.out.println(path+ "'s size is : " +file.length()+" bytes, it consumes " + (System.currentTimeMillis() - beforeTime) + " ms.");  
  95.         } catch (Exception e) {  
  96.             LOGGER.error(e.getMessage(), e);  
  97.         }  
  98.     }  
  99. }  

 其实还有方便的MD5生成方法,就是采用apache提供的开源项目 commons-codec.jar 自带的MD5生成。

如:

Java代码   收藏代码
  1. File file = new File(fileName);  
  2. String md5 = DigestUtils.md5Hex(new FileInputStream(file));  

 

附件中,我附带了一个方便日常生成MD5的jar,用来进行MD5的生成。

 

 

=========================== Google Guava ===============

Java代码   收藏代码
  1. import com.google.common.hash.HashCode;  
  2. import com.google.common.hash.Hashing;  
  3. import com.google.common.io.Files;  
  4.   
  5. import java.io.File;  
  6.   
  7. public class HashingExample {  
  8.   
  9.     public static void main(String[] args) throws Exception {  
  10.         print();  
  11.         File file = new File(  
  12.                 "D:/test/FileCopy.java");  
  13.           
  14.         HashCode hashCode = Files.hash(file, Hashing.md5());  
  15.         System.out.println(hashCode.toString());  
  16.     }  
  17.   
  18. }  

 

Java代码   收藏代码
  1. import com.google.common.hash.HashCode;  
  2. import com.google.common.hash.Hashing;  
  3. import com.google.common.io.Files;      
  4. /** 
  5.      * <pre> 
  6.      *  得到指定文件的MD5 
  7.      * @param file 文件 
  8.      * @param upper 是否大写 
  9.      * @return file文件的MD5 
  10.      * @throws IOException 
  11.      * </pre> 
  12.      */  
  13.     public static String createMd5(File file, boolean upper) throws IOException {  
  14.         HashCode hashCode = Files.hash(file, Hashing.md5());  
  15.         return upper ? hashCode.toString().toUpperCase() : hashCode.toString();  
  16.     }  

 有的时候我们不仅仅要对文件做MD5,也需要对字符串String进行MD5操作。下面的方法使用Guava写了一个生成字符串MD5的方法。

Java代码   收藏代码
  1. /** 
  2.  * <pre> 
  3.  * @param charSequence 
  4.  * @param charset 
  5.  * @param upper 
  6.  * @return 生成的MD5 
  7.  * </pre> 
  8.  */  
  9. public static String createMD5(CharSequence charSequence, Charset charset,  
  10.         boolean upper) {  
  11.     Preconditions.checkNotNull(charSequence, "charSequence is null");  
  12.     Preconditions.checkNotNull(charset, "charset is null");  
  13.   
  14.     String md5 = Hashing.md5().newHasher().putString(charSequence, charset)  
  15.             .hash().toString();  
  16.     return upper ? md5.toUpperCase() : md5;  
  17. }  

 示例:

Java代码   收藏代码
  1. String md5 = createMD5("hello", Charsets.UTF_8, true);  

  1. System.out.println(md5);//5D41402ABC4B2A76B9719D911017C592  

转自:http://kanpiaoxue.iteye.com/blog/1669100

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值