thieumao

File to MD5

Sep 14th, 2013
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.11 KB | None | 0 0
  1. /*
  2.  * To change this template, choose Tools | Templates
  3.  * and open the template in the editor.
  4.  */
  5. package test;
  6.  
  7. /**
  8.  *
  9.  * @author leo
  10.  */
  11. import java.io.FileInputStream;
  12. import java.security.MessageDigest;
  13.  
  14. public class FileToMD5 {
  15.  
  16.     @SuppressWarnings("empty-statement")
  17.     public static void main(String[] args) throws Exception {
  18.         String str = ToMD5("D:/Coding/HashCalc.exe");
  19.         System.out.println(str);
  20.     }
  21.  
  22.     private static String ToMD5(String FilePath) throws Exception {
  23.         MessageDigest md = MessageDigest.getInstance("MD5");
  24.         FileInputStream fis = new FileInputStream(FilePath);
  25.         byte[] dataBytes = new byte[1024];
  26.         int nread = 0;
  27.         while ((nread = fis.read(dataBytes)) != -1) {
  28.             md.update(dataBytes, 0, nread);
  29.         };
  30.         byte[] mdbytes = md.digest();
  31.         //convert the byte to hex
  32.         StringBuffer sb = new StringBuffer();
  33.         for (int i = 0; i < mdbytes.length; i++) {
  34.             sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
  35.         }
  36.         return sb.toString();
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment