创建 zip 存档时,什么构成重复条目
在 Java Web 应用程序中,我从各种内存中文件(存储为 byte[])创建一个 zip 文件。
这是代码的关键部分:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
for (//each member of a collection of objects) {
PDFDocument pdfDocument = //generate PDF for this member of the collection;
ZipEntry entry = new ZipEntry(pdfDocument.getFileName());
entry.setSize(pdfDocument.getBody().length);
zos.putNextEntry(entry);
zos.write(pdfDocument.getBody());//pdfDocument.getBody() returns byte[]
zos.closeEntry();
}
zos.close();
问题:在执行“putNextEntry()”行时,我有时会收到“ZipException:重复条目”。
PDF 文件本身肯定会有所不同,但它们可能具有相同的名称(“PDF_File_for_John_Smith.pdf”)。名称冲突是否足以导致此异常?
In a Java web application I am creating a zip file from various in-memory files (stored as byte[]).
Here's the key bit of code:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ZipOutputStream zos = new ZipOutputStream(baos);
for (//each member of a collection of objects) {
PDFDocument pdfDocument = //generate PDF for this member of the collection;
ZipEntry entry = new ZipEntry(pdfDocument.getFileName());
entry.setSize(pdfDocument.getBody().length);
zos.putNextEntry(entry);
zos.write(pdfDocument.getBody());//pdfDocument.getBody() returns byte[]
zos.closeEntry();
}
zos.close();
The problem: I'm sometimes getting a "ZipException: duplicate entry" when doing the "putNextEntry()" line.
The PDF files themselves will certainly be different, but they may have the same name ("PDF_File_for_John_Smith.pdf"). Is a name collision sufficient to cause this exception?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您不能在 zip 存档(同一文件夹中)中存储 2 个具有相同名称的条目,就像文件系统中的同一文件夹中不能有 2 个具有相同名称的文件一样。
编辑;虽然从技术上讲 zip 文件格式允许这样做,但处理 ZIP 档案的 Java API 却不允许这样做。
You can't store 2 entries with the same same name in a zip archive(in the same folder), much like you can't have 2 files with the same name in the same folder in a filesystem.
Edit; And while technically the zip file format allows this, the Java API for dealing with ZIP archives does not.
是的——如果您需要保存多个具有相同文件名的文件,您可以在 ZIP 文件中使用目录结构。
Yes -- you can use a directory structure inside your ZIP file if you need to hold multiple files with the same file name.
我相信是这样。 Zip 最初旨在归档目录结构,因此它希望文件名是唯一的。您可以添加目录来分隔文件(如果需要,还可以提供额外的信息来区分它们)。
I believe so. Zip was originally intended to archive a directory structure, so it expects filenames to be unique. You could add directories to keep your files separated (and provide extra information to differentiate them, if you want).