java獲取檔案md5碼
阿新 • • 發佈:2019-01-31
最近下載了一些檔案,不是官方的,為了核對MD5碼寫了一個java版本的,小工具。
package pri.yang.MD5; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.apache.commons.codec.binary.Hex; public class BigFileMD5 { static MessageDigest MD5 = null; static{ try{ MD5 = MessageDigest.getInstance("MD5"); }catch(NoSuchAlgorithmException e){ e.printStackTrace(); } } public static void main(String[] args){ if(args.length < 1){ System.out.println("need one argument as file path!"); }else{ String filePath = args[0]; //File file = new File("F:\\BaiduYunDownload\\jdk-7u79-linux-x64.tar.gz"); File file = new File(filePath); if(!file.exists()){ System.out.println("incorrect file path!"); }else{ String md5 = getMD5(file); System.out.println("===============MD5==============="); System.out.println(md5); System.out.println("===============MD5==============="); } } } /** * 對一個檔案獲取md5值 * @return md5串 */ public static String getMD5(File file) { FileInputStream fileInputStream = null; try { fileInputStream = new FileInputStream(file); byte[] buffer = new byte[8192]; int length; while ((length = fileInputStream.read(buffer)) != -1) { MD5.update(buffer, 0, length); } return new String(Hex.encodeHex(MD5.digest())); } catch (FileNotFoundException e) { e.printStackTrace(); return null; } catch (IOException e) { e.printStackTrace(); return null; } finally { try { if (fileInputStream != null) fileInputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } }