简体   繁体   中英

How do I write XML files directly to a zip archive?

What is the proper way to write a list of XML files using JAXB directly to a zip archive without using a 3rd party library.

Would it be better to just write all the XML files to a directory and then zip?

As others pointed out, you can use the ZipOutputStream class to create a ZIP-file. The trick to put multiple files in a single ZIP-file is to use the ZipEntry descriptors prior to writing (marshalling) the JAXB XML data in the ZipOutputStream . So your code might look similar to this one:


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();
  }
}

The "proper" way — without using a 3rd party library — would be to use java.util.zip.ZipOutputStream .

Personally, though, I prefer TrueZip .

TrueZIP is a Java based plug-in framework for virtual file systems (VFS) which provides transparent access to archive files as if they were just plain directories.

I don't know what JAXB has to do with anything, nor XML - file contents are file contents. Your question is really "How can I output characters directly to a zip archive"

To do that, open a ZipOututStream and use the API to create entries then write contents to each entry. Remember that a zip archive is like a series of named files within the archive.

btw, ZipOututStream is part of the JDK (ie it's not a "library")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM