以下是一个获取文件 MD5 值的 Java 程序示例:

import java.io.*;
import java.security.*;

public class FileMD5 {

    public static void main(String[] args) {
        String filePath = 'file.txt'; // 文件路径
        try {
            // 创建文件输入流
            FileInputStream fis = new FileInputStream(filePath);
            // 创建MD5对象
            MessageDigest md = MessageDigest.getInstance('MD5');
            // 读取文件内容
            byte[] buffer = new byte[1024];
            int len;
            while ((len = fis.read(buffer)) != -1) {
                md.update(buffer, 0, len);
            }
            // 计算MD5值
            byte[] md5Bytes = md.digest();
            // 将MD5值转换为字符串
            StringBuilder sb = new StringBuilder();
            for (byte b : md5Bytes) {
                sb.append(String.format('%02x', b & 0xff));
            }
            String md5 = sb.toString();
            System.out.println('MD5值:' + md5);
            // 关闭文件输入流
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

在该程序中,首先获取文件路径,然后创建文件输入流和 MD5 对象。接着使用文件输入流读取文件内容,并将内容传递给 MD5 对象进行计算。计算完成后,将 MD5 值转换为字符串格式并输出。最后,关闭文件输入流。

Java 获取文件 MD5 值:完整代码示例和解释

原文地址: https://www.cveoy.top/t/topic/lu5x 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录