如何在 Java ZIP 中不压缩存储 EPUB mimetype 文件
数据小陈
结论
EPUB 的 mimetype 条目要同时满足三个条件:第一,它必须是 ZIP 里的第一个条目;第二,压缩方法必须是 ZipEntry.STORED,也就是不压缩;第三,内容必须正好是 application/epub+zip,不能带 BOM、换行或其他额外字节。只调用 zos.setLevel(0) 并不能满足要求,因为条目的 method 还是 DEFLATED,只是 deflate 级别变成了 0,校验器仍可能把它当成压缩条目。
原因
ZipOutputStream.setLevel() 只影响之后 DEFLATED 条目的 deflate 级别,没法把条目改成 STORED。在 7zip 里,mimetype 的 Size 和 Packed Size 分别是 20 和 22,说明该条目仍带有额外开销,应改成 STORED。
修复步骤
- 先写
mimetype,再写其他条目。 - 把该
ZipEntry的 method 设为setMethod(ZipEntry.STORED)。 - STORED 条目要设置
setSize()、setCompressedSize()和setCrc()。size 用原始字节长度,CRC 用CRC32计算。 - 写完
mimetype并调用closeEntry()后,再写其他文件。其他文件列表里不能包含mimetype。 - 校验时确认
mimetype是第一个条目,Method 为 Stored,Packed Size 等于 Size。
代码示例
Path epubContentsPath = Path.of(epubContentsFolder);
Path epubFilePath = epubContentsPath.resolveSibling("book.epub");
Path mimetypePath = epubContentsPath.resolve("mimetype");
byte[] mimetypeBytes = Files.readAllBytes(mimetypePath);
CRC32 crc = new CRC32();
crc.update(mimetypeBytes);
try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(epubFilePath.toFile()))) {
ZipEntry mimetypeEntry = new ZipEntry("mimetype");
mimetypeEntry.setMethod(ZipEntry.STORED);
mimetypeEntry.setSize(mimetypeBytes.length);
mimetypeEntry.setCompressedSize(mimetypeBytes.length);
mimetypeEntry.setCrc(crc.getValue());
zos.putNextEntry(mimetypeEntry);
zos.write(mimetypeBytes);
zos.closeEntry();
List<Path> otherFiles;
try (Stream<Path> stream = Files.list(epubContentsPath)) {
otherFiles = stream
.filter(p -> !p.getFileName().toString().equals("mimetype"))
.collect(Collectors.toCollection(ArrayList::new));
}
ZipUtility.zip(otherFiles, zos);
}
如果 mimetype 内容固定,也可以直接使用:
byte[] mimetypeBytes = "application/epub+zip".getBytes(StandardCharsets.US_ASCII);
注意事项
- 在
mimetype之前不要写入任何 ZIP 条目。 - 不要用
setLevel(0)代替setMethod(ZipEntry.STORED)。 - STORED 条目必须提供正确的 size、compressedSize 和 CRC,否则可能抛出异常。
- 文件名必须是根目录下的
mimetype,不能写成Mimetype或OEBPS/mimetype。 - 内容不要带换行或 BOM。按规范,它应该是 20 字节的
application/epub+zip。 - 如果
ZipUtility.zip()内部会关闭流或重新创建条目,就要调整封装逻辑,确保它不会重写mimetype,也不会改变条目顺序。
备注:内容仅供参考。
