java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java计算文件MD5值

Java计算文件MD5值几种实现方式(支持大文件)

作者:ecexy78041

MD5是由Ron Rivest设计的一种加密哈希函数,它能够生成一个唯一的128位(16字节)哈希值,这篇文章主要介绍了Java计算文件MD5值几种实现方式(支持大文件)的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

在 Java 中计算文件的 MD5 值,特别是对于大文件,需要使用流式处理以避免内存溢出。以下是几种实现方式:

方法1:使用 MessageDigest 和 FileInputStream(标准方式)

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

public class FileMD5Calculator {
    
    public static String calculateMD5(File file) throws IOException, NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[8192]; // 8KB缓冲区
            int length;
            while ((length = fis.read(buffer)) != -1) {
                md.update(buffer, 0, length);
            }
        }
        return bytesToHex(md.digest());
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static void main(String[] args) {
        try {
            File file = new File("large_file.zip");
            String md5 = calculateMD5(file);
            System.out.println("MD5: " + md5);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

方法2:使用 Apache Commons Codec(简化版)

如果你项目中已经使用了 Apache Commons Codec,可以使用更简洁的方式:

import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

public class FileMD5Calculator {
    
    public static String calculateMD5(File file) throws IOException {
        try (FileInputStream fis = new FileInputStream(file)) {
            return DigestUtils.md5Hex(fis);
        }
    }

    public static void main(String[] args) {
        try {
            File file = new File("large_file.zip");
            String md5 = calculateMD5(file);
            System.out.println("MD5: " + md5);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

方法3:使用 Java NIO(高性能版)

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileMD5Calculator {
    
    public static String calculateMD5(Path path) throws IOException, NoSuchAlgorithmException {
        MessageDigest md = MessageDigest.getInstance("MD5");
        try (FileChannel channel = FileChannel.open(path, StandardOpenOption.READ)) {
            ByteBuffer buffer = ByteBuffer.allocateDirect(8192); // 直接缓冲区
            while (channel.read(buffer) != -1) {
                buffer.flip();
                md.update(buffer);
                buffer.clear();
            }
        }
        return bytesToHex(md.digest());
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder();
        for (byte b : bytes) {
            String hex = Integer.toHexString(0xff & b);
            if (hex.length() == 1) {
                hexString.append('0');
            }
            hexString.append(hex);
        }
        return hexString.toString();
    }

    public static void main(String[] args) {
        try {
            Path path = Path.of("large_file.zip");
            String md5 = calculateMD5(path);
            System.out.println("MD5: " + md5);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

方法4:使用 Guava 库

如果你使用 Google Guava 库:

import com.google.common.hash.Hashing;
import com.google.common.io.Files;

import java.io.File;
import java.io.IOException;

public class FileMD5Calculator {
    
    public static String calculateMD5(File file) throws IOException {
        return Files.hash(file, Hashing.md5()).toString();
    }

    public static void main(String[] args) {
        try {
            File file = new File("large_file.zip");
            String md5 = calculateMD5(file);
            System.out.println("MD5: " + md5);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

性能比较

注意事项

选择哪种方法取决于你的项目环境和需求。如果项目已经使用了 Apache Commons Codec 或 Guava,使用相应的方法会更方便;否则,标准方式或 NIO 方式都是不错的选择。

总结

到此这篇关于Java计算文件MD5值几种实现方式(支持大文件)的文章就介绍到这了,更多相关Java计算文件MD5值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文