CompressionUtil

来源:互联网 发布:seo效果检测步骤包括 编辑:程序博客网 时间:2024/06/06 18:01

1、调用

使用

CompressionUtil.zip2(Map<String, InputStream> in, OutputStream out) 方法

压缩为一个export-wsdl-20141023135549.zip的压缩包并自动下载

包括:

1、各服务名称文件夹 及子文件夹下3个文件 

2、校验码文件md5checksum.txt



 
md5checksum.txt文件内容:


  

注意:

1、Map<String, InputStream> in :

key为各文件名

value为各文件内容InputStream流

 

2、FilenameUtils.getName(path)

数据库中文件路径SERVER_ABS_PATH为:

/home/esbapp/lightesb/SYSFILE/1403612785951/SB_FI_ORS_InquiryPaymentApplicationInfoSrv/MsgHeader.xsd

 

获取的结果为MsgHeader.xsd

FilenameUtils.getName(path) a/b/c.txt --> c.txt a.txt     --> a.txt a/b/c     --> c a/b/c/    --> ""

  

数据库表格式

ESB_WSDL_FILE:


 

ESB_FILE(一个表,数据太长分开了):


 

 
视图ESB_WSDL_FILE_V省略

 

代码:

@RequestMapping(value = "esbService/exportWsdl.do", method = RequestMethod.GET)@ResponseBodypublic void exportWsdl(@RequestParam String info, HttpServletResponse response){//logger.debug("exportWsdl begin...");//logger.debug("parm : " + info);// 判断参数非空if(StringUtils.isNotEmpty(info)){/*** 构建Map<Long, String> basePath * <srvId,srvName> 用于下面由srvId获取srvName,构建srvName文件夹* info = srvId1:srvName1,srvId2:srvName2,...* 无需关注*/// zip包基础路径Map<Long, String> basePath = new HashMap<Long, String>();// 要下载WSDL的服务idList<Long> srvId = new ArrayList<Long>();String[] srvInfo = info.split(",");for(String si : srvInfo){String[] s = si.split(":");Long id = null;String srvName = null;try {id = Long.parseLong(s[0]);srvName = s[1];} catch (Exception e) {logger.error("exportWsdl parse parm error... " + si);continue;}srvId.add(id);basePath.put(id, srvName);}logger.debug("parse parm pass...");/*** =======================================* 压缩并自动下载* 重点关注部分* =======================================*/// 获取wsdl文件清单List<EsbWsdlFileV> ewf = esbServiceVDS.getWsdlFileList(srvId);//logger.debug("file list num : " + ewf.size());// detail为md5checksum.txt文件内容StringBuffer detail = new StringBuffer();detail.append("md5 checksum").append("\n");detail.append("\n");Long timestamp = System.currentTimeMillis();Map<String, InputStream> in = new HashMap<String, InputStream>();for(EsbWsdlFileV f : ewf){                        //文件真实路径String path = f.getServerAbsPath();                        //生成的文件,如ESB_EOM_E12_ImportOrderUrgeInfoSrv/MsgHeader.xsdString zipPath = basePath.get(f.getServiceId()) + "/" + FilenameUtils.getName(path);try {in.put(zipPath, new FileInputStream(new File(path)));detail.append(f.getMd5CheckSum()).append("\t").append(zipPath).append("\n");} catch (FileNotFoundException e) {logger.error(path + " not found...");}}detail.append("\n");detail.append(String.format("generated by project %s", SysConfigCache.getConfigByName(Constants.VERSION))).append("\n");detail.append(String.format("%1$tF %1$tT", timestamp)).append("\n");detail.append("Copyright (c) 2004-2013 A-Company").append("\n");//logger.debug("zip files parm : " + in);try {in.put("md5checksum.txt", IOUtils.toInputStream(detail.toString(), "UTF-8"));} catch (IOException e1) {logger.error("can not generate file list...");}// httpheader设置response.setContentType("application/x-msdownload;");  response.setHeader("Content-disposition", "attachment; filename = export-wsdl-" + String.format("%1$tY%1$tm%1$td%1$tH%1$tM%1$tS", timestamp) + ".zip");// 将wsdl文件压缩至请求流中try {CompressionUtil.zip2(in, response.getOutputStream());} catch (IOException e) {e.printStackTrace();logger.error("exportWsdl zip error...");}}logger.debug("exportWsdl end...");}

 

 

2、工具类:

import java.io.BufferedInputStream;import java.io.BufferedOutputStream;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.Map;import org.apache.tools.tar.TarEntry;import org.apache.tools.tar.TarOutputStream;import org.apache.tools.zip.ZipEntry;import org.apache.tools.zip.ZipFile;import org.apache.tools.zip.ZipOutputStream;public class CompressionUtil {private static final int BUFFEREDSIZE = 1024;/** * 将文件解压缩到指定目录 *  * @param srcFile * @param descDir * @throws IOException */public static void unzip(File srcFile, String descDir) throws IOException {// 创建解压目录new File(descDir).mkdirs();ZipFile zipFile = new ZipFile(srcFile);String strPath, gbkPath, strtemp;File tempFile = new File(descDir);strPath = tempFile.getAbsolutePath();@SuppressWarnings("rawtypes")java.util.Enumeration e = zipFile.getEntries();while (e.hasMoreElements()) {org.apache.tools.zip.ZipEntry zipEnt = (ZipEntry) e.nextElement();gbkPath = zipEnt.getName();if (zipEnt.isDirectory()) {strtemp = strPath + File.separator + gbkPath;File dir = new File(strtemp);dir.mkdirs();continue;} else {// 读写文件InputStream is = zipFile.getInputStream(zipEnt);BufferedInputStream bis = new BufferedInputStream(is);gbkPath = zipEnt.getName();strtemp = strPath + File.separator + gbkPath;// 建目录String strsubdir = gbkPath;for (int i = 0; i < strsubdir.length(); i++) {if (strsubdir.substring(i, i + 1).equalsIgnoreCase("/")) {String temp = strPath + File.separator+ strsubdir.substring(0, i);File subdir = new File(temp);if (!subdir.exists())subdir.mkdir();}}FileOutputStream fos = new FileOutputStream(strtemp);BufferedOutputStream bos = new BufferedOutputStream(fos);int c;while ((c = bis.read()) != -1) {bos.write((byte) c);}bos.close();fos.close();}}}/** * 解压指定路径的文件至指定目录 *  * @param srcFilepath * @param descDir * @throws IOException */public static void unzip(String srcFilepath, String descDir)throws IOException {File srcFile = new File(srcFilepath);unzip(srcFile, descDir);}/** * 解压文件到当前目录 *  * @param srcFile * @throws IOException */public static void unzip(File srcFile) throws IOException {unzip(srcFile, srcFile.getParent());}/** * 解压指定路径的文件至当前目录 *  * @param srcFilepath * @throws IOException */public static void unzip(String srcFilepath) throws IOException {File srcFile = new File(srcFilepath);unzip(srcFile, srcFile.getParent());}/** * 压缩zip格式的压缩文件 *  * @param inputFile *            需压缩文件 * @param out *            输出压缩文件 * @param base *            ZipEntry name * @throws IOException */private static void zip(File inputFile, ZipOutputStream out, String base)throws IOException {if (inputFile.isDirectory()) {File[] inputFiles = inputFile.listFiles();out.putNextEntry(new ZipEntry(base + "/"));base = base.length() == 0 ? "" : base + "/";for (int i = 0; i < inputFiles.length; i++) {zip(inputFiles[i], out, base + inputFiles[i].getName());}} else {if (base.length() > 0) {out.putNextEntry(new ZipEntry(base));} else {out.putNextEntry(new ZipEntry(inputFile.getName()));}FileInputStream in = new FileInputStream(inputFile);try {int c;byte[] by = new byte[BUFFEREDSIZE];while ((c = in.read(by)) != -1) {out.write(by, 0, c);}} catch (IOException e) {throw e;} finally {in.close();}}}/** * 压缩zip格式的压缩文件 *  * @param inputFile *            需压缩文件 * @param zipFilename *            输出文件及详细路径 * @throws IOException */public static void zip(File inputFile, String zipFilename)throws IOException {ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFilename));try {zip(inputFile, out, "");} catch (IOException e) {throw e;} finally {out.close();}}/** * 压缩zip格式的压缩文件 *  * @param inputFilename *            压缩的文件或文件夹及详细路径 * @param zipFilename *            输出文件名称及详细路径 * @throws IOException */public static void zip(String inputFilename, String zipFilename)throws IOException {zip(new File(inputFilename), zipFilename);}/** * 压缩tar格式的压缩文件 *  * @param inputFilename *            压缩文件 * @param tarFilename *            输出路径 * @throws IOException */public static void tar(String inputFilename, String tarFilename)throws IOException {tar(new File(inputFilename), tarFilename);}/** * 压缩tar格式的压缩文件 *  * @param inputFile *            压缩文件 * @param tarFilename *            输出路径 * @throws IOException */public static void tar(File inputFile, String tarFilename)throws IOException {TarOutputStream out = new TarOutputStream(new FileOutputStream(tarFilename));try {tar(inputFile, out, "");} catch (IOException e) {throw e;} finally {out.close();}}/** * 压缩tar格式的压缩文件 *  * @param inputFile *            压缩文件 * @param out *            输出文件 * @param base *            结束标识 * @throws IOException */private static void tar(File inputFile, TarOutputStream out, String base)throws IOException {if (inputFile.isDirectory()) {File[] inputFiles = inputFile.listFiles();out.putNextEntry(new TarEntry(base + "/"));base = base.length() == 0 ? "" : base + "/";for (int i = 0; i < inputFiles.length; i++) {tar(inputFiles[i], out, base + inputFiles[i].getName());}} else {if (base.length() > 0) {out.putNextEntry(new TarEntry(base));} else {out.putNextEntry(new TarEntry(inputFile.getName()));}FileInputStream in = new FileInputStream(inputFile);try {int c;byte[] by = new byte[BUFFEREDSIZE];while ((c = in.read(by)) != -1) {out.write(by, 0, c);}} catch (IOException e) {throw e;} finally {in.close();}}}/** * @param files <k, v> *        k zip包中的路径 *        v 待压缩的文件 * @param out 输出流 */public static void zip(Map<String, File> files, OutputStream out) throws IOException {ZipOutputStream zos = new ZipOutputStream(out);for(String path : files.keySet()){zip(files.get(path), zos, path);}zos.close();}/** * 流压缩 *  * @param in 输入流 * @param out 输出流 * @param name 压缩包中路径 * @throws IOException */private static void zip(InputStream in, ZipOutputStream out, String name)throws IOException {out.putNextEntry(new ZipEntry(name));try {int c;byte[] by = new byte[BUFFEREDSIZE];while ((c = in.read(by)) != -1) {out.write(by, 0, c);}} catch (IOException e) {throw e;} finally {in.close();}}/** * 流压缩 *  * @param in * @param out * @throws IOException */public static void zip2(Map<String, InputStream> in, OutputStream out) throws IOException {ZipOutputStream zos = new ZipOutputStream(out);for(String path : in.keySet()){zip(in.get(path), zos, path);}zos.close();}/*public static void main(String[] args) throws IOException {ZipOutputStream zos = new ZipOutputStream(new File("D:/btest/jjx.zip"));zip(new File("D:/atest/build.xml"), zos, "srv1/build.xml");zip(new File("D:/atest/jaxws-custom.xml"), zos, "srv2/jaxws-custom.xml");}*/}

 。。

 

 

 

 

 

 

 

 

原创粉丝点击