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

虽然是个小问题吧。

文件处理时的经验提升!

相关推荐
幻想趾于现实3 分钟前
C# Winform 入门(2)之发送邮件
开发语言·c#
SoFlu软件机器人7 分钟前
Go/Rust 疯狂蚕食 Java 市场?老牌语言的 AI 化自救之路
java·golang·rust
半盏茶香9 分钟前
启幕数据结构算法雅航新章,穿梭C++梦幻领域的探索之旅——堆的应用之堆排、Top-K问题
java·开发语言·数据结构·c++·python·算法·链表
hweiyu0018 分钟前
idea如何让打开的文件名tab多行显示
java·ide·intellij-idea·idea·intellij idea
小吴先生66631 分钟前
Groovy 规则执行器,加载到缓存
java·开发语言·缓存·groovy
星星不打輰41 分钟前
Spring基于注解进行开发
java·spring
陈大爷(有低保)42 分钟前
Spring中都用到了哪些设计模式
java·后端·spring
秋风&萧瑟1 小时前
【QT】QT的多界面跳转以及界面之间传递参数
开发语言·qt
骑牛小道士1 小时前
JAVA- 锁机制介绍 进程锁
java·开发语言
郭涤生1 小时前
Chapter 1: Historical Context_《C++20Get the details》_notes
开发语言·c++20