Kee*_*rox 0 java zip copy docx
我正在编写一个工具来在DOCX文件中进行一些小文本替换,这是一种压缩格式.我的方法是ZipEntry使用a将原始文件中的条目内容复制到修改后的文件中ZipOutputStream.对于大多数DOCX文件,这种方法效果很好,但偶尔我会遇到ZipException有关我写的内容与其中包含的元信息ZipEntry(通常是压缩大小的差异)之间的差异的问题.
这是我用来复制内容的代码.为简洁起见,我删除了错误处理和文档处理; 到目前为止,我还没有遇到过文档条目的问题.
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();
Run Code Online (Sandbox Code Playgroud)
将ZipEntry对象直接复制ZipFile到另一个对象的正确或惯用方法是什么?
我找到了一种避免错误的解决方法.通过创建ZipEntry仅具有名称字段集的新内容,我可以毫无问题地复制内容.
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);
if (read > 0) {
outputStream.write(buffer,0,read);
}
}
in.close();
}
outputStream.closeEntry();
}
outputStream.close();
Run Code Online (Sandbox Code Playgroud)
但是,我这种方法丢失了存储在原始字段中的任何元信息ZipEntry(例如:comment,extra).API文档不清楚这是否重要.