1 File file = new File("cos_code2003.bin"); 2 System.out.println(file.length()); 3 byte[] data = new byte[(int) file.length()]; 4 if (file.exists()) { 5 FileInputStream fis; 6 try { 7 fis = new FileInputStream(file); 8 fis.read(data); 9 } catch (FileNotFoundException e) { 10 e.printStackTrace(); 11 } catch (IOException e) { 12 e.printStackTrace(); 13 } 14 }else{ 15 System.out.println("wenjian buzun"); 16 } 17 18 String a = computeMd5(data); 19 System.out.println(a); 20 } 21 22 private static String computeMd5(byte[] origin) { 23 byte[] ret = null; 24 try { 25 MessageDigest md5 = MessageDigest.getInstance("MD5"); 26 ret = md5.digest(origin); 27 28 StringBuilder hexString = new StringBuilder(); 29 for (int i = 0; i < ret.length; i++) { 30 String h = Integer.toHexString(0xFF & ret[i]); 31 while (h.length() < 2) { 32 h = "0" + h; 33 } 34 hexString.append(h); 35 } 36 return hexString.toString(); 37 } catch (NoSuchAlgorithmException e) { 38 e.printStackTrace(); 39 } 40 41 return "AV"; 42 }
md5校驗不難,就是知道一個MessageDigest類,獲取實例,直接調用digest方法就可以了。不過校驗后得到的是一個數量為16的byte數組,要轉換成一個32位的16進制校驗和,還需要作一下轉換,注意這里用了一個StringBuilder類,把字節和0XFF進行與操作就可以了。另外注意的是當字節數少於16的時候要加一個前綴0,這里用的表示法是h.length,其它也有一些表示如0X10,其實是一樣的。最后轉成string就可以了。
另外注意這里的File文件的構造函數里面的文件名的寫法file,這里應該是java工程根目錄下的文件名,而不是和代碼在一個地方的文件名。
上面的md5校驗在計算超過2GB的大文件就會有問題,因為一個Int數組的最大只有2GB,2的31次方,否則內存會撐不住。
這里再給出一個方法,
private static String checkMd5(File f) { FileInputStream fis = null; byte[] rb = null; DigestInputStream digestInputStream = null; try { fis = new FileInputStream(f); MessageDigest md5 = MessageDigest.getInstance("md5"); digestInputStream = new DigestInputStream(fis, md5); byte[] buffer = new byte[4096]; while (digestInputStream.read(buffer) > 0) ; md5 = digestInputStream.getMessageDigest(); rb = md5.digest(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); }finally{ try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } StringBuilder sb = new StringBuilder(); for (int i = 0; i < rb.length; i++) { String a = Integer.toHexString(0XFF & rb[i]); if (a.length() < 2) { a = '0' + a; } sb.append(a); } return sb.toString(); }
這個方法,經測試2.7GB文件的MD5沒有出錯。
