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

虽然是个小问题吧。

文件处理时的经验提升!

相关推荐
扯淡的闲人1 天前
多语言编码Agent解决方案(4)-Eclipse插件实现
java·ide·eclipse
杨杨杨大侠1 天前
Atlas Mapper 教程系列 (7/10):单元测试与集成测试
java·开源·github
叽哥1 天前
Kotlin学习第 7 课:Kotlin 空安全:解决空指针问题的核心机制
android·java·kotlin
Florence231 天前
GPU硬件架构和配置的理解
开发语言
guslegend1 天前
Java面试小册(3)
java
派葛穆1 天前
Unity-按钮实现场景跳转
java·unity·游戏引擎
弥巷1 天前
【Android】Viewpager2实现无限轮播图
java
李游Leo1 天前
JavaScript事件机制与性能优化:防抖 / 节流 / 事件委托 / Passive Event Listeners 全解析
开发语言·javascript·性能优化
虫小宝1 天前
返利app排行榜的缓存更新策略:基于过期时间与主动更新的混合方案
java·spring·缓存
SimonKing1 天前
告别繁琐配置!Retrofit-Spring-Boot-Starter让HTTP调用更优雅
java·后端·程序员