java获取文件md5值

前言

给客户交付的文件,客户需要验证md5值,客户java语言,记录下实现过程,很简单。


代码

import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileMD5Generator {

    public static String generateMD5(String filePath) {
        try {
            MessageDigest md5Digest = MessageDigest.getInstance("MD5");
            byte[] buffer = new byte[8192];

            try (FileInputStream fis = new FileInputStream(filePath)) {
                int bytesRead;
                while ((bytesRead = fis.read(buffer)) != -1) {
                    md5Digest.update(buffer, 0, bytesRead);
                }
            }

            byte[] md5Bytes = md5Digest.digest();

            // Convert the byte to hex format
            StringBuilder result = new StringBuilder();
            for (byte md5Byte : md5Bytes) {
                result.append(Integer.toString((md5Byte & 0xff) + 0x100, 16).substring(1));
            }

            return result.toString();
        } catch (NoSuchAlgorithmException | IOException e) {
            e.printStackTrace(); // Handle the exception according to your requirements
            return null;
        }
    }

    public static void main(String[] args) {
        String filePath = "path/to/your/file.txt"; // Replace with the actual file path
        String md5 = generateMD5(filePath);

        if (md5 != null) {
            System.out.println("MD5: " + md5);
        } else {
            System.out.println("Error generating MD5");
        }
    }
}

请替换 path/to/your/file.txt 为你实际文件的路径。这个 Java 代码会读取文件内容并生成相应的 MD5 值。

你可能感兴趣的:(java,开发语言)