1. 程式人生 > >JAVA獲取檔案的MD5值

JAVA獲取檔案的MD5值

1.推薦如下方法:

 /**
	  * 推薦此方法獲取檔案MD5
	  * @param path 檔案路徑
	  * @return
	  */
	 public static String getMd5File(String path){
			String md5 = null;
	        try {
	        	FileInputStream fis= new FileInputStream(path);    
				md5 = DigestUtils.md5Hex(IOUtils.toByteArray(fis));
				IOUtils.closeQuietly(fis);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return md5;    
	 }

2.下面這個方法也嘗試過,但不知道是個人程式碼問題還是方法問題,偶爾會出現IO異常,因為趕專案沒時間深究,先mark後續看看
	/**
	 * @param file
	 * @return
	 * @throws FileNotFoundException
	 */
	 public static String getMd5ByFile(File file) throws FileNotFoundException {  
         String value = null;  
         FileInputStream in = new FileInputStream(file);  
     try {  
         MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());  
         MessageDigest md5 = MessageDigest.getInstance("MD5");  
         md5.update(byteBuffer);  
         BigInteger bi = new BigInteger(1, md5.digest());  
         value = bi.toString(16);  
     } catch (Exception e) {  
         e.printStackTrace();  
     } finally {  
             if(null != in) {  
                 try {  
                 in.close();  
             } catch (IOException e) {  
                 e.printStackTrace();  
             }  
         }  
     }  
     return value;  
     }