简体   繁体   English

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

[英]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. 在不使用第三方库的情况下,使用JAXB将XML文件列表直接写入zip存档的正确方法是什么?

Would it be better to just write all the XML files to a directory and then zip? 将所有XML文件写入目录然后压缩会更好吗?

As others pointed out, you can use the ZipOutputStream class to create a ZIP-file. 正如其他人所指出的,您可以使用ZipOutputStream类来创建ZIP文件。 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 . 将多个文件放在单个ZIP文件中的技巧是在ZipOutputStream编写(编组)JAXB XML数据之前使用ZipEntry描述符。 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 . “正确”的方式 - 不使用第三方库 - 将使用java.util.zip.ZipOutputStream

Personally, though, I prefer TrueZip . 就个人而言,我更喜欢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. TrueZIP是一个基于Java的虚拟文件系统(VFS)插件框架,它提供对存档文件的透明访问,就像它们只是普通目录一样。

I don't know what JAXB has to do with anything, nor XML - file contents are file contents. 我不知道JAXB与任何事情有什么关系,XML文件内容也不是文件内容。 Your question is really "How can I output characters directly to a zip archive" 您的问题实际上是“如何将字符直接输出到zip存档”

To do that, open a ZipOututStream and use the API to create entries then write contents to each entry. 为此,打开ZipOututStream并使用API​​创建条目,然后将内容写入每个条目。 Remember that a zip archive is like a series of named files within the archive. 请记住,zip存档就像存档中的一系列命名文件。

btw, ZipOututStream is part of the JDK (ie it's not a "library") 顺便说一句, ZipOututStream是JDK的一部分(即它不是“库”)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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