• 导出:xml zip


    import java.util.zip.ZipOutputStream;
    import java.io.BufferedOutputStream;
    import java.io.DataOutputStream;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.math.BigDecimal;
    import java.nio.charset.Charset;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    import org.dom4j.Document;
    import org.dom4j.DocumentHelper;
    import org.dom4j.Element;
    import org.dom4j.io.OutputFormat;
    import org.dom4j.io.XMLWriter;
    //https://blog.csdn.net/yangymy/article/details/91375621
    public class Test1 {
    
        public static void main(String[] args) {
            createXml("aaa.eep");
        }
    
        /**
         * java生成xml并直接写入zip包
         * @param rootpath
         * @param fileName
         */
        public static void createXml(String fileName) {
            ZipOutputStream zipos = null;
            DataOutputStream os = null;
            InputStream in = null;
    
            try {
                zipos = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream("d:/123.zip")),
                        Charset.forName("UTF-8"));
                zipos.setMethod(ZipOutputStream.DEFLATED); // 设置压缩方法
                os = new DataOutputStream(zipos);
    
                Document doc = DocumentHelper.createDocument();
                doc.setXMLEncoding("UTF-8");
                // 根节点
                Element root = doc.addElement("根节点", "http://www.xxxxxx.cn");
                root.addNamespace("xsi", "http://www.xxxxxx.cn");
                root.addAttribute("name", "M0");
                // 子节点1
                createElement("子节点1", "M1", "子节点1", root);
                // 子节点2
                createElement("子节点2", "M2", "子节点2", root);
                // 子节点3
                Element child3 = createElement("子节点3", "M3", "", root);
                child3.addAttribute("年度", "2009");
                // 子节点3的子节点
                createElement("节点3的子节点1", "M31", 100, child3);
                createElement("节点3的子节点2", "M32", 55.5, child3);
                createElement("节点3的子节点3", "M33", new Date(), child3);
    
                zipos.putNextEntry(new ZipEntry(fileName));
                OutputFormat outputFormat = OutputFormat.createPrettyPrint();
                outputFormat.setEncoding("UTF-8");
                XMLWriter writer = new XMLWriter(os, outputFormat);
                writer.setEscapeText(false);
                writer.write(doc);
    
                // 附件
                zipos.putNextEntry(new ZipEntry("123.txt"));
                OutputFormat outputFormat1 = OutputFormat.createPrettyPrint();
                outputFormat.setEncoding("UTF-8");
                XMLWriter writer1 = new XMLWriter(os, outputFormat1);
                writer1.setEscapeText(false);
                writer1.write("asdasdasdas");
    
    //            in = new FileInputStream("d:/123.txt");
    //            if (in != null) {
    //                byte[] b = new byte[1024 * 10];
    //                int length = 0;
    //                while ((length = in.read(b)) != -1) {
    //                    os.write(b, 0, length);
    //                }
    //            }
    
                zipos.closeEntry();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (zipos != null) {
                    try {
                        zipos.close();
                    } catch (Exception e2) {
                        e2.printStackTrace();
                    }
                }
                if (os != null) {
                    try {
                        os.close();
                    } catch (Exception e2) {
                        e2.printStackTrace();
                    }
                }
                if (in != null) {
                    try {
                        in.close();
                    } catch (Exception e2) {
                        e2.printStackTrace();
                    }
                }
            }
        }
    
        public static Element createElement(String tag, String name, Object text, Element parent) {
            Element element = parent.addElement(tag);
            if (element != null) {
                element.addAttribute("name", name);
                if (text == null)
                    text = "";
                String str = "";
                if (text instanceof Date) {
                    Date d = (Date) text;
                    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    str = format.format(d);
                } else if (text instanceof BigDecimal) {
                    str = text.toString();
                } else {
                    str = String.valueOf(text);
                }
                if (!str.trim().equals("")) {
                    element.addText(str);
                }
            }
            return element;
        }
    
    }
    import org.slf4j.Logger;
    import org.slf4j.LoggerFactory;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.Iterator;
    import java.util.List;
    import java.util.zip.ZipEntry;
    import java.util.zip.ZipOutputStream;
    
    @RestController
    @RequestMapping("xxxx")
    public class DownLoadController {
        private static final Logger logger = LoggerFactory.getLogger(UrlFilesToZip.class);
        //http://localhost:8099//xxxx/multipleDownLoad?urls=www.baidu.com&destFileName=123
        /**
         * 下载多个文件这 @return
         */
        @RequestMapping("/multipleDownLoad")
        public static void getFile(String urls, String destFileName, HttpServletResponse response) throws Exception, IOException {
            List<String> urlList = new ArrayList<>();
            for (String id : StringUtils.splitToList(urls, ",")) urlList.add(id);
            try {
                String filename = new String((destFileName + ".zip").getBytes("UTF-8"), "ISO8859-1");/*控制文件名编码*/
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                ZipOutputStream zos = new ZipOutputStream(bos);
                UrlFilesToZip s = new UrlFilesToZip();
                int idx = 1;
                String postfix = "";
                for (String oneFile : urlList) {
                    if (!(oneFile == null || oneFile.indexOf(".") == -1)) {/*如果图片地址为null或者地址中没有"."就返回""*/
                        postfix = oneFile.substring(oneFile.lastIndexOf(".") + 1).trim().toLowerCase();
                    }
                    if (!org.springframework.util.StringUtils.isEmpty(postfix)) postfix = "." + postfix;
                    zos.putNextEntry(new ZipEntry(destFileName + idx + postfix));
                    byte[] bytes = s.getImageFromURL(oneFile);
                    zos.write(bytes, 0, bytes.length);
                    zos.closeEntry();
                    idx++;
                }
                zos.close();
                response.setContentType("application/octet-stream; charset=utf-8");/* response.setContentType("application/force-download");// 设置强制下载不打开*/
                response.addHeader("Content-Disposition", "attachment;fileName=" + filename);/* 设置文件名*/
                OutputStream os = response.getOutputStream();
                os.write(bos.toByteArray());
                os.close();
            } catch (FileNotFoundException ex) {
                logger.error("FileNotFoundException", ex);
            } catch (Exception ex) {
                logger.error("Exception", ex);
            }
        }
    }
    
    class StringUtils {
        public static List<String> splitToList(String str, String regex) {
            if (org.springframework.util.StringUtils.isEmpty(str)) return null;
            else {
                ArrayList resultList = new ArrayList();
                List resultObject =  Arrays.asList((str.split(regex)));
                Iterator i$ = resultObject.iterator();
                while (i$.hasNext()) {
                    Object obj = i$.next();
                    resultList.add(obj.toString());
                }
                return resultList;
            }
        }
    }
    
    /**
     * Created by Admin on 2017/10/19.
     */
     class UrlFilesToZip {
        private static final Logger logger = LoggerFactory.getLogger(UrlFilesToZip.class);/*根据文件链接把文件下载下来并且转成字节码*/
    
        public byte[] getImageFromURL(String urlPath) {
            byte[] data = null;
            InputStream is = null;
            HttpURLConnection conn = null;
            try {
                URL url = new URL(urlPath);
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true);/* conn.setDoOutput(true);*/
                conn.setRequestMethod("GET");
                conn.setConnectTimeout(6000);
                is = conn.getInputStream();
                if (conn.getResponseCode() == 200) data = readInputStream(is);
                else data = null;
            } catch (MalformedURLException e) {
                logger.error("MalformedURLException", e);
            } catch (IOException e) {
                logger.error("IOException", e);
            } finally {
                try {
                    if (is != null) is.close();
                } catch (IOException e) {
                    logger.error("IOException", e);
                }
                conn.disconnect();
            }
            return data;
        }
    
        public byte[] readInputStream(InputStream is) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int length = -1;
            try {
                while ((length = is.read(buffer)) != -1) baos.write(buffer, 0, length);
                baos.flush();
            } catch (IOException e) {
                logger.error("IOException", e);
            }
            byte[] data = baos.toByteArray();
            try {
                is.close();
                baos.close();
            } catch (IOException e) {
                logger.error("IOException", e);
            }
            return data;
        }
    
    }
  • 相关阅读:
    黑客网银木马服务器曝光 14家银行网银遭监控 狼人:
    卡巴斯基实验室CE0来华启动卡巴斯基安全中国行 狼人:
    天清汉马UTM获“北京市自主创新产品”称号 狼人:
    IBM称欧亚受Conficker病毒感染最严重 狼人:
    卡巴斯基联手功夫巨星成龙 五月鸟巢开唱 狼人:
    微软4月14日起不再为所有XP用户提供安全补丁 狼人:
    卡巴斯基爱好者见面会 卡巴斯基先生与卡fans亲密互动 狼人:
    愚人节黑客以身试法 人民法院被挂马 狼人:
    微软:97%电子邮件属于垃圾邮件 狼人:
    4月3日 尤金.卡巴斯基在北大精彩演讲 狼人:
  • 原文地址:https://www.cnblogs.com/xyyou/p/12409535.html
Copyright © 2020-2023  润新知