我正在编写一个工具来在 DOCX 文件(一种压缩格式)中进行一些小的文本替换。我的方法是复制ZipEntry
使用以下命令将原始文件中条目的内容写入修改后的文件中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();
直接复制的正确或惯用方法是什么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();
但是,此方法会丢失原始字段中存储的任何元信息ZipEntry
(例如:评论、额外)。 API 文档并不清楚这是否重要。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)