How to write XML files directly to a zip archive?

What is the correct way to write a list of XML files using JAXB directly to a zip archive without using a third-party library.

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

+8
java xml zip jaxb
source share
3 answers

As others have pointed out, you can use the ZipOutputStream class to create a ZIP file. The trick to placing multiple files in a single ZIP file is to use ZipEntry descriptors before writing (sorting) JAXB XML data in ZipOutputStream . So your code might look something like this:

 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(); } } 
+10
source share

"The right way; without using a third-party library - it would use java.util.zip.ZipOutputStream .

Personally, I prefer TrueZip .

TrueZIP is a Java-based platform for virtual file systems (VFS) that provides transparent access to archive files as if they were just simple directories.

+3
source share

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

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

btw, ZipOututStream is part of the JDK (i.e. this is not a "library")

+1
source share

All Articles