将ZipEntry复制到新的ZipFile中的惯用方法是什么? [英] What is the idiomatic way to copy a ZipEntry into a new ZipFile?
问题描述
我在写一个工具,在DOCX文件中做一些小的文本替换,这是一个压缩格式。我的方法是使用 ZipOutputStream
将 ZipEntry
内容从原始文件中的条目复制到修改的文件。对于大多数DOCX文件,这很好,但偶尔我会遇到 ZipException
关于我写的内容和元信息之间的差异包含在 ZipEntry
(通常是压缩大小的差异)。
I'm writing a tool to do some minor text replacement in a DOCX file, which is a zipped format. My method is to copy ZipEntry
contents from entries in the original file into the modified file using a ZipOutputStream
. For most DOCX files this works well, but occasionally I will encounter ZipException
s regarding discrepancies between the contents I've written and the meta-information contained in the ZipEntry
(usually a difference in compressed size).
这里是我用来复制内容的代码。为了简洁,我已经省略了错误处理和文档处理;我到目前为止还没有文档条目的问题。
Here's the code I'm using to copy over contents. I've stripped out error handling and document processing for brevity; I haven't had issues with the document entry so far.
ZipFile original = new ZipFile(INPUT_FILENAME);
ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(OUTPUT_FILE));
Enumeration entries = original.entries();
byte[] buffer = new byte[512];
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();
if ("word/document.xml".equalsIgnoreCase(entry.getName())) {
//perform special processing
}
else{
outputStream.putNextEntry(entry);
InputStream in = original.getInputStream(entry);
while (0 < in.available()){
int read = in.read(buffer);
outputStream.write(buffer,0,read);
}
in.close();
}
outputStream.closeEntry();
}
outputStream.close();
直接复制 ZipEntry
对象从一个 ZipFile
到另一个?
What is the proper or idiomatic way to directly copy ZipEntry
objects from one ZipFile
to another?
推荐答案
发现了一个避免错误的解决方法。通过创建一个新的 ZipEntry
只有名称字段设置,我可以复制内容没有问题。
I have found a workaround that avoids the error. By creating a new ZipEntry
with only the name field set I'm able to copy over contents without issue.
ZipFile original = new ZipFile(INPUT_FILENAME);
ZipOutputStream outputStream = new ZipOutputStream(new FileOutputStream(OUTPUT_FILE));
Enumeration entries = original.entries();
byte[] buffer = new byte[512];
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();
if ("word/document.xml".equalsIgnoreCase(entry.getName())) {
//perform special processing
}
else{
// create a new empty ZipEntry
ZipEntry newEntry = new ZipEntry(entry.getName());
// outputStream.putNextEntry(entry);
outputStream.putNextEntry(newEntry);
InputStream in = original.getInputStream(entry);
while (0 < in.available()){
int read = in.read(buffer);
outputStream.write(buffer,0,read);
}
in.close();
}
outputStream.closeEntry();
}
outputStream.close();
< > ZipEntry (eg:comment,extra)。 API文档并不清楚这是否重要。
However, I this method loses any meta-information stored in the fields of original ZipEntry
(e.g.: comment, extra). The API docs aren't clear on whether this is important.
这篇关于将ZipEntry复制到新的ZipFile中的惯用方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!