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);
    }
}

虽然是个小问题吧。

文件处理时的经验提升!

相关推荐
天上掉下来个程小白15 分钟前
开发环境搭建-06.后端环境搭建-前后端联调-Nginx反向代理和负载均衡概念
java·运维·spring boot·后端·nginx·负载均衡·苍穹外卖
试着生存18 分钟前
java根据List<Object>中的某个属性排序(数据极少,顺序固定)
java·python·list
酷爱码18 分钟前
2025DNS二级域名分发PHP网站源码
开发语言·php
_星辰大海乀19 分钟前
LinkedList 双向链表
java·数据结构·链表·list·idea
MSTcheng.22 分钟前
【C语言】动态内存管理
c语言·开发语言·算法
热心市民小汪23 分钟前
管理conda下python虚拟环境
开发语言·python·conda
小韩学长yyds30 分钟前
Java调用第三方HTTP接口:从入门到实战
java·开发语言·http
McQueen_LT32 分钟前
聊天室Python脚本——ChatGPT,好用
开发语言·python·chatgpt
苏十八32 分钟前
JavaEE Servlet02
java·服务器·网络·java-ee·json
如鱼得水不亦乐乎34 分钟前
C Primer Plus 第十章练习
c语言·开发语言