利用jdom.jar导出成.xml文件,并压缩,并下载所压缩的文件

  方法比较麻烦,主要是Document和Element生成xml:dataSetMap   key为表名,value为json串

项目里是jdom.jar,所以也没换,比jsom1.0和2.0老,方法大同小异
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.output.XMLOutputter;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.model.ModelUtil;

import com.system.sourceclass.SourceClass;

  /**

     * 导出xml,可以导所有
     *
     * @param dataSetMap
     * @throws Exception
     */
    public int buildXMLByMap(Map dataSetMap) throws Exception {
        if (UtilValidate.isEmpty(dataSetMap)) {
            return -1;
        }
        JSONArray ja = this.nodeJson;
        String s = "";
        Map<String, String> parentMapName = new HashMap<String, String>();
        Map<String, String> childMapName = new HashMap<String, String>();
        for (int q = 0; q < ja.length(); q++) {// 分离页面选择的表名和字段名
            s = ja.getString(q);// {"id":"EmpA004","name":"学历及学位子集","isParent":true,"parentId":""}
            JSONObject jb = (JSONObject) ja.get(q);
            if (s.contains("\"isParent\":true")) {
                parentMapName.put(jb.getString("id"), jb.getString("name"));
            } else {
                childMapName.put(jb.getString("id"), jb.getString("name"));
            }
        }
        String rootUrl = System.getProperty("user.dir");
        String xmlUrl = rootUrl + xmlFilePath;
        // 检查c盘如果不存在此路径,就创建
        // File file = new File(xmlUrl);
        // String path = chenkIsNoCreateFile(file);
        // 创建根节点 并设置它的属性 ;
        Element root = new Element("ROOT").addAttribute("tableCount", ""
                + dataSetMap.size());
        // 将根节点添加到文档中;
        Document Doc = new Document(root);
        String tableName = "";
        String fieldList = "";
        String fieldName = "";
        String fieldValue = "";
        String[] entitys = null;
        // String[] fileds = null;
        String tablePK = "";
        String idValue = "";
        JSONObject jb = null;
        Iterator ite = null;
        FileOutputStream fis = null;
        HashMap<String, String> map = (HashMap<String, String>) dataSetMap;
        ExportFile ef = new ExportFile(this.isAllRecord, this.isMedia,
                this.nodeJson);
        List listEntity = ef.getEntity();// 得到页面选中的表名
        for (Entry entry : map.entrySet()) {
            tableName = (String) entry.getKey();
            Element tableElement = new Element(tableName);
            for (Entry tname : parentMapName.entrySet()) {// 遍历页面的parentMapName,xml设置<EmpA001
                                                            // name="人员基本情况表">
                if (tableName.equals((String) tname.getKey())) {
                    // 创建节点 tableName,并设置属性
                    tableElement.addAttribute("name", tname.getValue()
                            .toString());
                }
            }
            fieldList = entry.getValue().toString();
            entitys = fieldList.replaceAll("\\}\\,\\{", "\\}\\;\\{").split(";");// 得到每行值
            for (int w = 0; w < entitys.length; w++) {//
                if (w == 0) {// w=0时,得到此表的pk名,EMP_ID
                    tablePK = SourceClass.getDBPK(SourceClass
                            .getCategoryRootStr(tableName));// 得到主键名EMP_ID
                }

                String mapPkKey = ModelUtil.dbNameToClassName(tablePK);// 返回处理过的pk名,EMP_ID--->EmpId
                jb = new JSONObject(entitys[w]);
                idValue = jb.getString(mapPkKey);

                Element pkElement = new Element(tablePK).addAttribute("id",
                        idValue);// 为数据库每一行创建一个element,表的主键
                tableElement.addContent(pkElement);
                // fileds = entitys[w].split("\\,");// 得到属性及对应值
                ite = jb.keys();
                while (ite.hasNext()) {
                    String key = (String) ite.next();
                    for (int j = 0; j < listEntity.size(); j++) {
                        if (tableName.equals((String) listEntity.get(j))) {// map里的在数据库里查到的表名和页面选的一致时,才去比对表里的字段
                            List listField = ef.getFieldByEntity(tableName);// 得到页面选择的所有的属性
                            for (int k = 0; k < listField.size(); k++) {
                                if (key.equals(listField.get(k))) {
                                    fieldName = key;
                                    fieldValue = jb.getString(key);// 用空替换"
                                    // 给 节点添加子节点并赋值;
                                    Element eend = new Element(fieldName)
                                            .setText(fieldValue);
                                    pkElement.addContent(eend);
                                    for (Entry cname : childMapName.entrySet()) {
                                        if (fieldName.equals((String) cname
                                                .getKey())) {
                                            eend.addAttribute("name", cname
                                                    .getValue().toString());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            root.addContent(tableElement);
            // 使xml文件 缩进效果
            // Format format = Format.getCompactFormat();
            // format.setIndent("  ");
            XMLOutputter xMLOut = new XMLOutputter();
            // xMLOut.setTrimText(true);
            xMLOut.setIndent("  ");// 设置分隔符
            xMLOut.setNewlines(true);
            fis = new FileOutputStream(xmlUrl + this.sessionId + tableName
                    + ".xml");
            xMLOut.output(Doc, fis);
            // elements.addContent("");
            root.removeContent(tableElement);
        }
        fis.close();
        // 生成压缩文件
        // String zipFileName = "f:/exportXMLbook.zip";
        String zipUrl = rootUrl + zipFilePath;
        String zipFileName = rootUrl + fileName + this.sessionId
                + "exportXMLbook.zip";
        boolean createOver = ZipUtil.ZipMultiFile(xmlUrl, zipFileName);
        // 生成之后删除所有的xml所在文件夹 path:f:/exportXML/
        if (!createOver) {
            return -2;
        }
        return 1;

    }


生成zip类:

package com.importAndExport.Export;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {

    /**
     * 压缩文件,一次性压缩多个文件,文件存放至一个文件夹中
     *
     * @param filepath
     *            要压缩的文件夹
     * @param zippath
     *            压缩的文件存放的位置+文件名.zip
     * @return
     */

    public static boolean ZipMultiFile(String filepath, String zippath) {
        try {
            File file = new File(filepath);// 要被压缩的文件夹
            File zipFile = new File(zippath);
            InputStream input = null;
            ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(
                    zipFile));
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (int i = 0; i < files.length; ++i) {
                    input = new FileInputStream(files[i]);
                    zipOut.putNextEntry(new ZipEntry(file.getName()
                            + File.separator + files[i].getName()));
                    int temp = 0;
                    while ((temp = input.read()) != -1) {
                        zipOut.write(temp);
                    }
                    input.close();
                }
            }
            zipOut.close();
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

}

下载生成的zip文件:

package com.fileupdown;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.newskysoft.filefilter.FileEncrypter;

public class DownLoadServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        // 得到要下载的文件名
        String fileNames = request.getParameter("path"); //
        // 判断是否是绝对路径
        String isAbsolutePath = request.getParameter("isAbsolutePath"); //
        String[] fileName = fileNames.split(",");// 多文件删除

        String sessionId = request.getSession().getId();
        // 工程根路径
        String rootUrl = System.getProperty("user.dir");
        String miPath = "\\components\\ops\\webapp";

        String FolderModule = request.getParameter("FolderModule");

        if (fileName.length > 0) {
            for (int j = 0; j < fileName.length; j++) {
                if (!fileName[j].equals("") || fileName[j] != null) {
                    // 得到要下载的文件
                    String singleFile = fileName[j];
                    if ("1".equals(isAbsolutePath)) {
                        int idx = singleFile.lastIndexOf("/");
                        String pathPart = singleFile.substring(0, idx + 1);
                        String namePart = singleFile.substring(idx + 1);
                        singleFile = rootUrl + miPath + pathPart + sessionId
                                + namePart;
                    }
                    File file = new File(singleFile);
                    String realname = fileName[j].substring(fileName[j]
                            .lastIndexOf("\\") + 1);
                    // 设置响应头,控制浏览器下载该文件
                    response.setHeader(
                            "content-disposition",
                            "attachment;filename="
                                    + URLEncoder.encode(realname, "UTF-8"));
                    // 如果文件存在
                    if (file.exists()) {
                        response.setContentType(realname.substring(realname
                                .lastIndexOf(".") + 1)); // 设置返回的文件类型
                        if ("GpmsInterface".equals(FolderModule)) {
                            InputStream in = new FileInputStream(singleFile);
                            OutputStream out = response.getOutputStream();

                            // 写文件
                            int b;
                            while ((b = in.read()) != -1) {
                                out.write(b);
                            }

                            in.close();
                            out.close();
                        } else {
                            FileEncrypter fileEncrypter = new FileEncrypter();
                            try {

                                fileEncrypter.decrypt(singleFile, response);// 文件解密
                            } catch (Exception e) {
                                try {
                                    throw new Exception("文件解密失败");
                                } catch (Exception e1) {
                                    // TODO Auto-generated catch block
                                    e1.printStackTrace();
                                }
                            }
                        }
                        if ("1".equals(isAbsolutePath)) {
                            // DeleteFile deleteFile = new DeleteFile();
                            // deleteFile.deleteFile(sessionId);
                        }
                    } else {

                        response.getWriter().write("文件不存在");
                    }
                }
            }

        }
    }


    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值