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

虽然是个小问题吧。

文件处理时的经验提升!

相关推荐
chxii4 分钟前
1.8 axios详解
开发语言·前端·javascript
Yang-Never4 分钟前
设计模式 -> 策略模式(Strategy Pattern)
android·开发语言·设计模式·kotlin·android studio·策略模式
Java&Develop16 分钟前
Java中给List<T> 对象集合去重
java·开发语言
poemyang17 分钟前
“代码跑着跑着,就变快了?”——揭秘Java性能幕后引擎:即时编译器
java·java虚拟机·编译原理·jit·即时编译器
都叫我大帅哥19 分钟前
全面深入解析Hystrix:Java分布式系统的"防弹衣" 🛡️
java·spring boot·spring cloud
沐知全栈开发28 分钟前
Perl 格式化输出
开发语言
wjs20241 小时前
SQLite 注入:深入理解与防范策略
开发语言
杨DaB1 小时前
【项目实践】在系统接入天气api,根据当前天气提醒,做好plan
java·后端·spring·ajax·json·mvc
椰椰椰耶2 小时前
【Spring】SpringBoot自动注入原理分析,@SpringBootApplication、@EnableAutoConfiguration详解
java·spring boot·spring
晨非辰3 小时前
#C语言——刷题攻略:牛客编程入门训练(四):运算(二)
c语言·开发语言·经验分享·学习·visual studio