Original: http://www.open-open.com/code/view/1424930488031
ImportJava.io.File;ImportJava.io.FileInputStream;Importjava.io.IOException;ImportJava.nio.MappedByteBuffer;ImportJava.nio.channels.FileChannel;Importjava.security.MessageDigest;Importjava.security.NoSuchAlgorithmException; Public classFilemd5utils {protected Static CharHexdigits[] = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' d ', ' e ', ' F '}; protected StaticMessageDigest messagedigest =NULL; Static{ Try{messagedigest= Messagedigest.getinstance ("MD5"); }Catch(nosuchalgorithmexception e) {System.err.println (filemd5utils.class. GetName () + "initialization failed, MessageDigest does not support Md5util."); E.printstacktrace (); } } /*** Calculate the MD5 of the file *@paramthe absolute path of the filename file *@return * @throwsIOException*/ Public StaticString getfilemd5string (String fileName)throwsioexception{File F=NewFile (fileName); returngetfilemd5string (f); } /*** Calculate file MD5, overloaded method *@paramFile Object *@return * @throwsIOException*/ Public StaticString getfilemd5string (file file)throwsioexception{FileInputStream in=Newfileinputstream (file); FileChannel CH=In.getchannel (); Mappedbytebuffer Bytebuffer= Ch.map (FileChannel.MapMode.READ_ONLY, 0, File.length ()); Messagedigest.update (Bytebuffer); returnBuffertohex (Messagedigest.digest ()); } Private StaticString Buffertohex (bytebytes[]) { returnBuffertohex (Bytes, 0, bytes.length); } Private StaticString Buffertohex (byteBytes[],intMintN) {stringbuffer StringBuffer=NewStringBuffer (2 *N); intK = m +N; for(intL = m; L < K; l++) {Appendhexpair (bytes[l], stringbuffer); } returnstringbuffer.tostring (); } Private Static voidAppendhexpair (bytebt, StringBuffer StringBuffer) { CharC0 = hexdigits[(BT & 0xf0) >> 4]; CharC1 = HEXDIGITS[BT & 0xf]; Stringbuffer.append (C0); Stringbuffer.append (C1); } Public Static voidMain (string[] args)throwsIOException {String fileName= "F:\\test01\\1.txt"; String Str= "d0970714757783e6cf17b26fb8e2298f"; String str2= "ea3ed20b6b101a09085ef09c97da1597"; System.out.println (Str.equals (str2)); System.out.println (getfilemd5string (fileName)); } }
Java Compute file MD5 value code