方法比較麻煩,主要是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);
}
}