java 将字符串生成xml文件并压缩成zip
时间: 2024-01-26 20:04:45 浏览: 144
XML文件在Java程序中的基本运用.zip
可以使用Java中的DOM和ZipOutputStream来实现将字符串生成xml文件并压缩成zip的功能。以下是一个简单的实现示例:
```java
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
public class XmlZipper {
public static void main(String[] args) throws Exception {
// 生成xml字符串
String xmlString = "<root><message>Hello World!</message></root>";
// 将xml字符串转换为Document对象
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new ByteArrayInputStream(xmlString.getBytes()));
// 创建zip文件
File zipFile = new File("example.zip");
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
// 将xml写入zip文件
ZipEntry xmlEntry = new ZipEntry("example.xml");
zipOut.putNextEntry(xmlEntry);
ByteArrayOutputStream xmlOut = new ByteArrayOutputStream();
document.setXmlStandalone(true);
document.normalize();
document.getDocumentElement().normalize();
XmlUtils.writeXml(document, xmlOut);
zipOut.write(xmlOut.toByteArray());
xmlOut.close();
zipOut.closeEntry();
// 关闭zip文件
zipOut.finish();
zipOut.close();
}
public static class XmlUtils {
public static void writeXml(Document document, ByteArrayOutputStream out) throws Exception {
javax.xml.transform.TransformerFactory tf = javax.xml.transform.TransformerFactory.newInstance();
javax.xml.transform.Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(javax.xml.transform.OutputKeys.ENCODING, "UTF-8");
transformer.setOutputProperty(javax.xml.transform.OutputKeys.INDENT, "yes");
javax.xml.transform.dom.DOMSource source = new javax.xml.transform.dom.DOMSource(document);
javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(out);
transformer.transform(source, result);
}
}
}
```
这段代码将生成一个名为example.zip的压缩文件,并在其中包含了一个名为example.xml的xml文件。你可以使用ZipFile类来解压缩该文件,并读取其中的xml内容。
阅读全文