我正在尝试将两个 XML 文件打包到一个 zip 文件中: XML 是用
org.w3c.dom.*
生成的,我试图将它们直接转换为 ZipOutputStream
。单个文件示例:
try (final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final ZipOutputStream zos = new ZipOutputStream(bos)) {
var zipEntry = new ZipEntry("file1.xml");
zos.putNextEntry(zipEntry);
final DOMSource source = new DOMSource(document);
final StreamResult result = new StreamResult(zos);
transformer.transform(source, result);
}
而
document
是 (org.w3c.dom.Document) 且 transformer
是 (javax.xml.transform.Transformer):
final TransformerFactory transformerFactory = TransformerFactory.newInstance();
final Transformer transformer = transformerFactory.newTransformer();
final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
final Document document = documentBuilderFactory.newDocumentBuilder().newDocument();
但我总是收到无效的 ZIP 文件。如果我调试它并尝试读取
ZipEntry
我会得到 EOFException
:
final ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
final ZipInputStream zis = new ZipInputStream(bis);
final ZipEntry entry = zis.getNextEntry();
assertEquals("file1.xml", entry.getName());
final String xmlString = IOUtils.toString(zis);//Here it throws Unexpected end of ZLIB input stream
有什么想法吗?
如果删除 DOM 代码并直接处理 ZipOutputStream(并添加对 closeEntry 的调用):
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.zip.*;
public class ZipTest {
public static void main(String[] args) {
try (final FileOutputStream fos = new FileOutputStream("test.zip");
final ZipOutputStream zos = new ZipOutputStream(fos)
) {
var zipEntry = new ZipEntry("file1.xml");
zos.putNextEntry(zipEntry);
zos.write("<test></test>".getBytes(StandardCharsets.UTF_8));
zos.closeEntry();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
然后它会生成一个有效的 ZIP 文件,所以我假设问题出在你的 DOM 代码上。您能否提供一个完整的示例,因为我无法根据您迄今为止提供的内容重新创建您的问题。