是否可以组合ZipOutputStream和DigestOutputstream?

问题描述 投票:1回答:2

我需要先确定.zip文件的校验和,然后才能确保文件的完整性。

目前,我有以下内容:

        for (File file : zipCandidates) {
            InputStream fileInputStream = new BufferedInputStream(new FileInputStream(file));
            ZipUtils.addDataToZip(zipStream, fileInputStream, file.getName());
            boolean deleted = file.delete();
            if (!deleted) {
                log.error("Failed to delete temporary file {} : {}", file.getName(), file.getAbsolutePath());
            }
        }
        zipStream.close();

        // checksum and filesize
        long fileSize = zipFile.length();
        InputStream fileInputStream = FileUtils.openInputStream(zipFile);
        BufferedInputStream bufferedFileInputStream = new BufferedInputStream(fileInputStream);
        String checksum = DigestUtils.md5Hex(bufferedFileInputStream);

        bufferedFileInputStream.close();


        // upload
        fileInputStream = FileUtils.openInputStream(zipFile);
        bufferedFileInputStream = new BufferedInputStream(fileInputStream);
        val writer = writerFactory.createWriter(blobName, fileSize, checksum);
        writer.write(bufferedFileInputStream);

        bufferedFileInputStream.close();

毋庸置疑,这是非常低效的,因为我必须两次读取每个.zip文件才能在上传之前辨别其校验和。

有没有什么方法可以将我的ZipOutputStreamDigestOutputstream结合起来,这样我就可以在编写zip文件时更新我的​​校验和?不幸的是,由于输出流必须是ZipOutputStream,我不能简单地装饰它(即new DigestOutputStream(zipStream, digest))。

java stream zip checksum
2个回答
2
投票

不幸的是,由于输出流必须是ZipOutputStream,我不能简单地装饰它(即new DigestOutputStream(zipStream, digest))。

你不会想要,因为你想要消化压缩操作的结果,所以你需要用DigestOutputStream包装ZipOutputStream,即另一种方式:

try (ZipOutputStream zipStream = new ZipOutputStream(
                                   new DigestOutputStream(
                                     new FileOutputStream(zipFile),
                                     digest))) {
    // code adding zip entries here
}
String checksum = Hex.encodeHexString(digest.digest());

请注意使用try-with-resources确保您的ZipOutputStream始终正确关闭。


1
投票

你当然可以构造一个包含两个输出流的输出流(在你的特定情况下,一个是你的ZipOutputStream,另一个是你的DigestOutputStream)。您的新输出流实现会将它收到的每个字节写入两个包装的流。

这个用例很常见,你可能会找到一个满足你需求的开源版本(例如,this one from apache commons)。

© www.soinside.com 2019 - 2024. All rights reserved.