MessageDigest类封装得很不错,简单易用
不多说,直接上代码
import java.io.FileInputStream;import java.security.MessageDigest;import java.util.Scanner;public class MD5Test {
public static void main(String[] args) { System.out.print("输入文件名:"); Scanner inputFromConsole = new Scanner(System.in); String filename = inputFromConsole.nextLine(); try (FileInputStream inputFromFile = new FileInputStream(filename)) { MessageDigest md5 = MessageDigest.getInstance("MD5"); byte[] buffer = new byte[10 * 1024 * 1024]; int byteCount; while ((byteCount = inputFromFile.read(buffer)) != -1) { md5.update(buffer, 0, byteCount); } StringBuilder result = new StringBuilder(); byte[] digested = md5.digest(); for (byte e : digested) { String hexStr = Integer.toHexString(e & 255); if (hexStr.length() == 1) result.append('0'); result.append(hexStr); } System.out.println(result); } catch (Exception ex) { ex.printStackTrace(); } }}