如何将XML文件直接写入zip存档? [英] How do I write XML files directly to a zip archive?
问题描述
在不使用第三方库的情况下,使用JAXB将XML文件列表直接写入zip存档的正确方法是什么。
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.
仅仅更好吗?将所有XML文件写入目录然后压缩?
Would it be better to just write all the XML files to a directory and then zip?
推荐答案
正如其他人指出的那样,你可以使用 ZipOutputStream
用于创建ZIP文件的类。将多个文件放在一个ZIP文件中的技巧是在 ZipOutputStream中编写(编组)JAXB XML数据之前使用
。因此,您的代码可能与此类似: ZipEntry
描述符
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();
}
}
这篇关于如何将XML文件直接写入zip存档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!