如何将XML文件直接写入zip存档?

kdg*_*ill 8 java xml zip jaxb

在不使用第三方库的情况下,使用JAXB将XML文件列表直接写入zip存档的正确方法是什么?

将所有XML文件写入目录然后压缩会更好吗?

Jir*_*era 11

正如其他人所指出的,您可以使用ZipOutputStream该类来创建ZIP文件.将多个文件放在一个ZIP文件中的技巧是ZipEntry在编写(编组)JAXB XML数据之前使用描述符ZipOutputStream.因此,您的代码可能与此类似:


JAXBElement jaxbElement1 = objectFactory.createRoot(rootType);
JAXBElement jaxbElement2 = objectFactory.createRoot(rootType);

ZipOutputStream zos = null; 
try {
  zos = new ZipOutputStream(new FileOutputStream("xml-file.zip"));
  // add zip-entry descriptor
  ZipEntry ze1 = new ZipEntry("xml-file-1.xml");
  zos.putNextEntry(ze1);
  // add zip-entry data
  marshaller.marshal(jaxbElement1, zos);
  ZipEntry ze2 = new ZipEntry("xml-file-2.xml");
  zos.putNextEntry(ze2);
  marshaller.marshal(jaxbElement2, zos);
  zos.flush();
} finally {
  if (zos != null) {
    zos.close();
  }
}
Run Code Online (Sandbox Code Playgroud)