我需要先确定.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
文件才能在上传之前辨别其校验和。
有没有什么方法可以将我的ZipOutputStream
和DigestOutputstream
结合起来,这样我就可以在编写zip文件时更新我的校验和?不幸的是,由于输出流必须是ZipOutputStream
,我不能简单地装饰它(即new DigestOutputStream(zipStream, digest)
)。
不幸的是,由于输出流必须是
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
始终正确关闭。
你当然可以构造一个包含两个输出流的输出流(在你的特定情况下,一个是你的ZipOutputStream,另一个是你的DigestOutputStream)。您的新输出流实现会将它收到的每个字节写入两个包装的流。
这个用例很常见,你可能会找到一个满足你需求的开源版本(例如,this one from apache commons)。