Java中文件处理问题

事情起因是因为这句话:

复制代码
String md = DigestUtils.md5Hex(Files.newInputStream(Paths.get(filePath)));

这句话虽然返回了正确的md值,但是会锁住后续的文件操作。所以应该自己封装一个安全的函数使用try包裹住才好。

比方说改成这样:

java 复制代码
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class FileMD5Calculator {

    public static String calculateMD5(String filePath) {
        try (RandomAccessFile file = new RandomAccessFile(filePath, "r");
             FileChannel channel = file.getChannel()) {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            ByteBuffer buffer = ByteBuffer.allocate(8192); // 分配 8KB 的缓冲区
            int bytesRead = 0;
            while ((bytesRead = channel.read(buffer)) != -1) {
                buffer.flip(); // 切换至读模式
                digest.update(buffer);
                buffer.clear(); // 清空缓冲区,为下一次读取做准备
            }
            byte[] hash = digest.digest();
            return bytesToHex(hash);
        } catch (IOException | NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
    }

    private static String bytesToHex(byte[] bytes) {
        StringBuilder result = new StringBuilder();
        for (byte b : bytes) {
            result.append(String.format("%02x", b));
        }
        return result.toString();
    }

    public static void main(String[] args) {
        String filePath = "your_file_path_here";
        String md5 = calculateMD5(filePath);
        System.out.println("MD5: " + md5);
    }
}

虽然是个小问题吧。

文件处理时的经验提升!

相关推荐
吴声子夜歌2 分钟前
ApacheCommons——commons-cli(命令行参数解析)
java·开发语言·apache
小小猪的春天11 分钟前
Java 手写第一个 MCP Server:Spring AI MCP 半小时跑通
java·人工智能·spring boot·ai编程
find1star12 分钟前
LeetCode 141:环形链表
java·算法·leetcode·链表
今天AI了吗1 小时前
DeepSeek Harness 深度解析:从评测架构到实战落地
java·网络·数据库·人工智能·架构·java-ee
benchmark_cc1 小时前
REST API 和 Python SDK 应该怎么选?量化交易数据接口选型实战
开发语言·python·数据分析·pandas·量化交易·股票数据·quantdash
王的宝库1 小时前
Go 项目结构:从单文件到标准工程布局
开发语言·后端·golang
Tairitsu_H1 小时前
[C++] 深入理解红黑树:封装set与map
开发语言·c++·set·map·红黑树·模拟实现
许彰午1 小时前
27-AuthService登录链路
java·低代码·架构
泡海椒1 小时前
JQuick-Curl 性能分析:并发场景下的性能表现与调优,第三方接口调用不只要快写也要稳跑
java·开发语言·okhttp
小智老师PMP2 小时前
2026深度解析|PMP第八版与NPDP核心侧重点本质区别(管理类证书怎么选)
开发语言·分布式·算法·职场和发展·产品经理