将多个xml字符串文件 压缩成zip包输出到浏览器

  • 因为最近在工作中遇到要将多个xml文件压缩成zip包并输出到浏览器,所以特地记录下来,以备下次不时之需。废话不多说直接上代码…

  • ZipController 我这里是直接在本地模拟多个xml字符串数据的

    package com.xwfu.zip.controller;
    
    
    import com.xwfu.zip.util.ZipUtil;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.GetMapping;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    @Controller
    public class ZipController {
    
        @Autowired
        ZipUtil zipUtil;
    
        @GetMapping("/zip")
        public void testZip(HttpServletRequest request, HttpServletResponse response) throws IOException {
            List<String> files = new ArrayList<String>();
            for (int i = 0; i < 3; i++) {
                String str = "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n" +
                        "<Document>\n" +
                        "    <Events>\n" +
                        "        <Event Name=\"PurchaseWareHouseIn\" MainAction=\"WareHouseIn\">\n" +
                        "            <DataField>\n" +
                        "                <Data Code=\"83406830007604149938\" CorpOrderID=\"RFWL-RE210628000174\" ActDate=\"2021-06-29\" ToCorp=\"\" Actor=\"詹念\" ToCorpID=\"\"/>\n" +
                        "                <Data Code=\"83406830007605542766\" CorpOrderID=\"RFWL-RE210628000174\" ActDate=\"2021-06-29\" ToCorp=\"\" Actor=\"詹念\" ToCorpID=\"\"/>\n" +
                        "            </DataField>\n" +
                        "        </Event>\n" +
                        "    </Events>\n" +
                        "</Document>";
                files.add(str);
            }
            zipUtil.zipFiles(files, "testZip", request, response);
        }
    
    }
    
    
  • ZipUtil 生成压缩文件的工具类

    package com.xwfu.zip.util;
    
    import org.springframework.stereotype.Component;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.net.URLEncoder;
    import java.util.ArrayList;
    import java.util.LinkedList;
    import java.util.List;
    import java.util.UUID;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    @Component
    public class ZipUtil {
    
        public void zipFiles(List<String> srcFile, String zipFileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
            try {
    
                List<File> srcFiles = new ArrayList<File>();
                for (String str : srcFile) {
                    String path = UUID.randomUUID().toString().replaceAll("-", "") + ".xml";
                    File file = new File(path);
                    OutputStreamWriter osw = null;
                    BufferedWriter bw = null;
                    try {
                        osw = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
                        bw = new BufferedWriter(osw);
                        bw.write(str);
                        bw.flush();
                    } catch (Exception e) {
                        e.printStackTrace();
                    } finally {
                        if (bw != null) bw.close();
                        if (osw != null) osw.close();
                    }
                    srcFiles.add(file);
                }
                // 设置文件编码及相应消息头,防止中文乱码
                String userAgent = request.getHeader("user-agent").toLowerCase();
                //String exportFileName = "testZip";
                if (userAgent.contains("msie") || userAgent.contains("like gecko")) {
                    // win10 ie edge 浏览器 和其他系统的ie
                    zipFileName = URLEncoder.encode(zipFileName, "UTF-8");
                } else {
                    zipFileName = new String(zipFileName.getBytes("UTF-8"), "ISO-8859-1");
                }
                response.setCharacterEncoding("UTF-8");
                response.setContentType("multipart/form-data");
                response.setHeader("content-disposition", "attachment;filename=" + zipFileName + ".zip");
                //获取系统文件
                /*List<File> srcFiles = new LinkedList<File>();
                File fileGc = new File("D:\\GoogleDownloads\\2.txt");
                File fileJt = new File("D:\\GoogleDownloads\\1.txt");
                srcFiles.add(fileGc);
                srcFiles.add(fileJt);*/
    
    
                ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
                try {
                    for (int i = 0; i < srcFiles.size(); i++) {
                        File file = srcFiles.get(i);
                        byte[] buf = new byte[1024];
                        out.putNextEntry(new ZipEntry(file.getName()));
                        int len;
                        FileInputStream input = new FileInputStream(srcFiles.get(i));
                        while ((len = input.read(buf)) != -1) {
                            out.write(buf, 0, len);
                            out.flush();
                        }
                        input.close();
                        out.closeEntry();
                    }
                    out.close();
                } catch (Exception e) {
                    throw new RuntimeException("zipFile error from ZipUtils", e);
                } finally {
                    if (out != null) {
                        try {
                            out.close();
                        } catch (IOException e) {
                            System.out.println("ZipUtil toZip close exception" + e);
                        }
                    }
                }
            } catch (Exception e) {
                System.out.println(e.getMessage());
            }
        }
    
    }
    
    
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
可以使用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.xmlxml文件。你可以使用ZipFile类来解压缩文件,并读取其中的xml内容。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值