Ext上传zip包后台解压

21 篇文章 0 订阅
2 篇文章 0 订阅
importTemplate.jsp
<%@ page language="java" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="page" uri="/WEB-INF/tlds/paginated.tld"%>
<%@ include file="../common/language.jsp"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
<link href="../style/base<%=language_css%>.css" rel="stylesheet"
    type="text/css" />
<link rel="stylesheet" type="text/css"
    href="../js/ext/resources/css/ext-all.css"></link>
<%@ include file="../common/commonJS.jsp"%>
<script type="text/javascript" src="../js/ext/adapter/ext/ext-base.js"></script>
<script type="text/javascript" src="../js/ext/ext-all.js"></script>
<script type="text/javascript">
Ext.onReady( function() {
        Ext.QuickTips.init();//初始化Ext.QuickTips,以使得tip提示可用
        Ext.BLANK_IMAGE_URL = "../js/ext/resources/images/default/s.gif";
        /**    qtip,title,under,side都是只给出提示的方式,用side时,最好页面布局的form只有一列,否则,
        列宽控制不好,side提示容易被覆盖。*/
        Ext.form.Field.prototype.msgTarget = 'side';

        var btn = new Ext.Button(
                {
                    id : 'dd',
                    text : '<s:text name="msg.portalMS.jsp.file.browse"/> ',//浏览
                    listeners : {
                        render : function() {
                            var button_container = this.el.child("em");
                            button_container.position("relative");
                            this.input_file = Ext.DomHelper
                                    .append(
                                            button_container,
                                            {
                                                tag : "input",
                                                type : "file",
                                                size : 1,
                                                name : this.input_name || Ext.id(this.el),
                                                style : "z-index: 99999;position: absolute;display: block; border: none;cursor: pointer;"
                                            }, true);
                            this.input_file.setOpacity(0);
                            this.input_file.on("click", function(e) {
                                e.stopPropagation()
                            })
                            this.input_file.on("change", function(e) {
                                var value = this.input_file.dom.value;
                                panel.getForm().findField('fileValue').setValue(value);
                            }, this)
                            btn_cont = this.el.child("em");
                            btn_box = btn_cont.getBox();
                            this.input_file.setStyle("font-size",(btn_box.width * 0.5) + "px");
                            inp_box = this.input_file.getBox();
                            adj = {
                                x : 3,
                                y : 3
                            };
                            this.input_file.setLeft(btn_box.width - inp_box.width + adj.x + "px");
                            this.input_file.setTop(btn_box.height - inp_box.height + adj.y + "px")
                        }
                    }
                });

        var panel = new Ext.form.FormPanel(
                {
                /**
                web.xml
                    <servlet>
                        <servlet-name>UploadServlet</servlet-name>
                        <servlet-class>com.coship.dhm.portalMS.template.servlet.UploadServlet</servlet-class>
                        <load-on-startup>5</load-on-startup>
                    </servlet>
                    <servlet-mapping>
                        <servlet-name>UploadServlet</servlet-name>
                        <url-pattern>/template/uploadServlet</url-pattern>
                    </servlet-mapping>
                */                    
                    url : '../template/uploadServlet?t=' + new Date(),
                    autoScroll : true,
                    applyTo : 'form',
                    frame : true,
                    width : 550,
                    height : 130,
                    buttonAlign : 'center',
                    fileUpload : true,

                    title : '<s:text name="msg.portalMS.template.import" />',//模板文件
                    items : [ {
                        border : false,
                        layout : 'table',
                        items : [
                                {
                                    layout : 'form',
                                    // hideLabels : true, 隐藏标签
                                    border : false,
                                    labelAlign : 'right',
                                    style : 'padding-top:3px;',
                                    items : new Ext.form.TextField(
                                            {
                                                id : 'file',
                                                name : 'fileValue',
                                                fieldLabel : '<s:text name="msg.portalMS.template.file"/> '
                                            })
                                }, {
                                    border : false,
                                    style : 'padding-left:2px;',
                                    items : btn
                                }]
                    } ],

                    buttons : [ {
                        text : '<s:text name="msg.portalMS.template.upload.begin"/>',//开始上传
                        handler : function() {
                            var fileField = Ext.getCmp('file');
                            var fileValue = fileField.getValue();
                            if (Ext.isEmpty(fileValue)) {
                                Ext.Msg.alert(
                                                "<s:text name='msg.portalMS.template.system.tip'/>",
                                                "<s:text name='msg.portalMS.template.system.error.tip1'/>");
                                return;
                            } else {
                                if (-1 == fileValue.toLocaleLowerCase().lastIndexOf(".zip")) {
                                    Ext.Msg.alert(//上传的模板文件必须是zip文件!                                    
                                                    "<s:text name='msg.portalMS.template.system.tip'/>",
                                                    "<s:text name='msg.portalMS.template.system.error.tip2'/>");
                                    return;
                                }
                            }
                            //点击'开始上传'之后,将由这个function来处理。  
                            if (panel.form.isValid()) {//验证form, 本例略掉了                      
                                //显示进度条  
                                Ext.MessageBox
                                        .show( {
                                            title : '<s:text name="msg.portalMS.template.uploading"/>',
                                            width : 240,
                                            progress : true,
                                            closable : true,//正在上传文件
                                            progressText : '<s:text name="msg.portalMS.template.uploading"/>...'
                                        });

                                var submitUrl = '../template/uploadServlet?t=' + new Date();

                                //form提交  
                                panel.getForm().submit( {
                                    url : submitUrl,
                                    method : 'POST'
                                });
                                //设置一个定时器,每500毫秒向processController发送一次ajax请求  
                                var i = 0;
                                var timer = setInterval(
                                    function() {
                                        Ext.Ajax.request( {
                                                    //以后凡是在ajax的请求的url上面都要带上日期戳,  
                                                    url : '../template/processController.action?t=' + new Date(),
                                                    method : 'get',
                                                    //处理ajax的返回数据  
                                                    success : function(response,options) {
                                                        status = response.responseText
                                                                + " "
                                                                + i++;
                                                        var obj = Ext.util.JSON.decode(response.responseText);
                                                        if (obj.success == true) {
                                                            if (obj.finished) {
                                                                clearInterval(timer);
                                                                status = response.responseText;
                                                                Ext.MessageBox.updateProgress(
                                                                                1,
                                                                                'finished',
                                                                                'finished');
                                                                Ext.MessageBox.hide();
                                                                Ext.MessageBox
                                                                        .alert(
                                                                                "<s:text name='msg.portalMS.template.system.tip'/>",
                                                                                "<s:text name='msg.portalMS.template.system.success.tip'/>",
                                                                                function(e) {
                                                                                    var tempTemplateDir = obj.msg;
                                                                                    window.location.href = '../template/editTemplate.action?action=toAddInput&template.templatePath=' + tempTemplateDir;
                                                                                    return;
                                                                                });
                                                            } else {
                                                                Ext.MessageBox.updateProgress(
                                                                                obj.percentage,
                                                                                obj.msg);
                                                            }
                                                        } else {
                                                            Ext.Msg.alert(
                                                                            "<s:text name='msg.portalMS.template.system.tip'/>",
                                                                            obj.msg);
                                                        }
                                                    },
                                                    failure : function(response,options) {
                                                        clearInterval(timer);
                                                        Ext.Msg.alert(
                                                                        "<s:text name='msg.portalMS.template.system.error'/>",
                                                                        "<s:text name='msg.portalMS.template.system.error.tip'/>");
                                                    }
                                                });
                                        }, 500);
                            } else {
                                Ext.Msg
                                        .alert(//上线失败!
                                                "<s:text name='msg.portalMS.template.system.tip'/>",
                                                "<s:text name='msg.portalMS.template.tip.error'/>");
                            }
                        }
                    } ]
                });
    });

</script>
</head>
<body>
    <div class="r_main">
        <!---导航 --->
        <div class="r_nav">
            <div class="left">
                <img src="../images/nav_l.gif" width="5" height="29" />
            </div>
            <div class="ct">
                <s:text name="msg.portalMS.system.current.position" />
                <s:text name="msg.portalMS.template.guide.index" />
            </div>
            <div class="right">
                <img src="../images/nav_r.jpg" width="5" height="29" />
            </div>
        </div>
    </div>
    <div id="form">

    </div>
</body>

</html>


web.xml
    <servlet>
        <servlet-name>UploadServlet</servlet-name>
        <servlet-class>com.coship.dhm.portalMS.template.servlet.UploadServlet</servlet-class>
        <load-on-startup>5</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>UploadServlet</servlet-name>
        <url-pattern>/template/uploadServlet</url-pattern>
    </servlet-mapping>
    
文件上传处理类:
UploadServlet.java

package com.coship.dhm.portalMS.template.servlet;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

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

import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileItemIterator;
import org.apache.commons.fileupload.FileItemStream;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.ProgressListener;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.util.Streams;
import org.apache.commons.io.FileUtils;

import com.xxxxxx.ChineseCharacter;
import com.xxxxxx.dhm.common.config.impl.PropertiesFactory;
import com.xxxxxx.dhm.common.config.impl.XMLFactory;
import com.xxxxxx.dhm.portalMS.common.Constants;
import com.xxxxxx.dhm.portalMS.common.DebugLogHelper;
import com.xxxxxx.dhm.portalMS.common.PortalMSBeanFactory;
import com.xxxxxx.dhm.portalMS.common.SerConstants;
import com.xxxxxx.dhm.portalMS.common.util.ZIPUtil;
import com.xxxxxx.dhm.portalMS.exception.PortalMSException;
import com.xxxxxx.dhm.portalMS.template.entity.Template;
import com.xxxxxx.dhm.portalMS.template.service.ITemplateService;
import com.xxxxxx.dhm.portalMS.template.util.TemplateUtil;

/**
 * @author
 * @version
 * @see [相关类/方法]
 * @since
 */
public class UploadServlet extends HttpServlet
{
    private static final long serialVersionUID = 3632737193045318450L;

    private static final DebugLogHelper logger = new DebugLogHelper(UploadServlet.class);
    
    

    /** 模板service接口 */
    private ITemplateService templateService = (ITemplateService) PortalMSBeanFactory.getInstance().getBean("templateService");

    /**
     * Servlet初始化方法
     */
    public void init() throws ServletException
    {
        super.init();

        //获得web应用的上传路径
        /*
         *D:\tomcat_portal\webapps\portalMS\\uploads\\temp\ pub work his
         */
        createDir(SerConstants.TEMPLATE_TEMP);
        createDir(SerConstants.TEMPLATE_PUB);
        createDir(SerConstants.TEMPLATE_WORK);
        createDir(SerConstants.TEMPLATE_HIS);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
        logger.enterFuncDebugLog();
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/plain; charset=UTF-8");
        Template template = new Template();
        template.setUpdater(-1L);
        long currentTime = System.currentTimeMillis();
        ///D:/tomcat_portal/webapps/portalMS/uploads/temp/ ,1394764686793.zip
        File tempFile = new File(SerConstants.TEMPLATE_TEMP, currentTime
                + Constants.TEMPLATE_ZIP_POSTFIX.getStringValue());
        ///D:/tomcat_portal/webapps/portalMS/uploads/temp/1394764686793
        File outputDir = new File(SerConstants.TEMPLATE_TEMP + File.separator + currentTime);
        boolean isAdd = true;

        if (ServletFileUpload.isMultipartContent(request))
        {
            FileItemFactory factory = new DiskFileItemFactory();
            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setProgressListener(new UploadProgressListener(request));

            /** 模板文件最大值 */
            Integer templateZipMaxSize = XMLFactory.getValueInt("templateConfig.maxSize");
            if ((templateZipMaxSize * 1024 * 1024) < request.getContentLength())
            {
                errorSetting(request, PropertiesFactory.getValueString(ChineseCharacter.UPLOADSERVLET_TEMPLATE_TOO_BIG)
                        + templateZipMaxSize + "M, "
                        + PropertiesFactory.getValueString(ChineseCharacter.UPLOADSERVLET_NOT_ALLOWED_TO_UPLOAD));
                logger.exitFuncDebugLog();
                return;
            }

            try
            {
                setParameter(request, template, tempFile, upload);
                if (null != tempFile && tempFile.length() == 0)
                {
                    throw new IllegalArgumentException(PropertiesFactory
                            .getValueString(ChineseCharacter.UPLOADSERVLET_NOT_ALLOWED_EMPTY));
                }
                updateTempTemplate(request, response, template, currentTime, tempFile, outputDir, isAdd);
            }
            catch (Exception e)
            {
                errorSetting(request, PropertiesFactory
                        .getValueString(ChineseCharacter.UPLOADSERVLET_TEMPLATE_UPLLAD_FAIL));
                logger.exitFuncDebugLog();
                return;
            }
            finally
            {
                if (tempFile.exists() && !tempFile.delete())
                {
                    new Thread(new DelFileThread(tempFile)).start();
                }
            }
        }
        else
        {
            errorSetting(request, PropertiesFactory.getValueString(ChineseCharacter.UPLOADSERVLET_TEMPLATE_UPLLAD_FAIL));
            logger.exitFuncDebugLog();
            return;
        }
    }

    private void updateTempTemplate(HttpServletRequest request, HttpServletResponse response, Template template,
            long currentTime, File tempFile, File outputDir, boolean isAdd) throws Exception, PortalMSException,
            IOException
    {
        logger.enterFuncDebugLog();
        request.getSession().setAttribute("processFilePercentage", 0.3d);
        try
        {
            if (null != template.getTemplateId())
            {
                isAdd = false;
                outputDir = new File(SerConstants.TEMPLATE_WORK+ template.getCode());
                if (outputDir.exists())
                {
                    // 修改时,需先删除存在的模板文件
                    FileUtils.forceDelete(outputDir);
                }
            }
            // 新增时,需保证目录存在
            if (!outputDir.exists())
            {
                FileUtils.forceMkdir(outputDir);
            }

            request.getSession().setAttribute("processFilePercentage", 0.4d);
            boolean unZipResult = ZIPUtil.unZipSupportChinese(tempFile, outputDir.getPath());
            if (false == unZipResult)
            {
                throw new Exception();
            }
            request.getSession().setAttribute("processFilePercentage", 0.6d);
        }
        catch (Exception e)
        {
            logger.excepFuncDebugLog("unzip template zip file occur error! " + e.getMessage());
            throw new Exception(e);
        }

        if (false == isAdd)
        {
            try
            {
                TemplateUtil.reWriteIndexHtm(outputDir.getPath() + File.separator + template.getHomePage(),
                        Constants.TEMPLATE_GLOBAL_JS.getStringValue(), Constants.TEMPLATE_GLOBAL_VIEW_JS
                                .getStringValue());
            }
            catch (Exception e)
            {
                logger.excepFuncDebugLog("rewrite tempalte main page error. [templateMainPage = " + outputDir.getPath()
                        + File.separator + template.getHomePage() + "] " + e.getMessage());
            }

            Template busTemplate = null;
            try
            {
                busTemplate = (Template) templateService.findById(template.getTemplateId());
            }
            catch (Exception e1)
            {
                logger.excepFuncDebugLog("update template file occur error. get busTemplate occur error. ");
                throw new Exception();
            }

            if (null == busTemplate)
            {
                template.setStatus(0);
            }
            else
            {
                template.setStatus(5);
            }

            // 修改模板
            templateService.updateTempTemplate(template);
        }

        request.getSession().setAttribute("tempTemplateDir", currentTime + "");
        request.getSession().setAttribute("processFilePercentage", 1d);
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(
                "{success:true,msg:'"
                        + PropertiesFactory.getValueString(ChineseCharacter.UPLOADSERVLET_TEMPLATE_UPLLAD_SUCESS)
                        + "'}");
        logger.exitFuncDebugLog();
    }

    private void setParameter(HttpServletRequest request, Template template, File tempFile, ServletFileUpload upload)
            throws FileUploadException, IOException, FileNotFoundException
    {
        logger.enterFuncDebugLog();
        FileItemIterator fii = upload.getItemIterator(request);
        while (fii.hasNext())
        {
            FileItemStream fis = fii.next();
            if ((!fis.isFormField()) && (fis.getName().length() > 0))
            {
                InputStream in = fis.openStream();

                int availabe = in.available();
                int contentLength = request.getContentLength();
                logger.excepFuncDebugLog("availabe = " + availabe);
                logger.excepFuncDebugLog("contentLength = " + contentLength);

                BufferedOutputStream outStream = new BufferedOutputStream(new FileOutputStream(tempFile));
                Streams.copy(in, outStream, true);
            }
            else
            {
                if ("templateId".equals(fis.getFieldName()))
                {
                    template.setTemplateId(Long.parseLong((String) request.getParameter("templateId")));
                }
                else if ("templateCode".equals(fis.getFieldName()))
                {
                    template.setCode((String) request.getParameter("templateCode"));
                }
                else if ("homePage".equals(fis.getFieldName()))
                {
                    template.setHomePage((String) request.getParameter("homePage"));
                }
            }
        }
        logger.exitFuncDebugLog();
    }

    /**
     *
     * 设置错误信息
     * @param request
     * @param errorMes
     * @return void
     * @exception throws
     */
    private void errorSetting(HttpServletRequest request, String errorMes)
    {
        logger.excepFuncDebugLog("import template zip error. errorMes : " + errorMes);
        request.getSession().setAttribute("uploadPercentage", 1d);
        request.getSession().setAttribute("processFilePercentage", 1d);
        request.getSession().setAttribute("upFileErrorMes", errorMes);
    }

    /**
     *
     * 创建目录
     * @param dirPath
     * @return void
     * @exception throws
     */
    private void createDir(String dirPath)
    {
        File dir = new File(dirPath);
        if (!dir.exists())
        {
            try
            {
                FileUtils.forceMkdir(dir);
            }
            catch (IOException e)
            {
            }
        }
    }

    /**
     *
     * 删除临时模板文件线程类
     * @author
     * @version
     * @since
     */
    static class DelFileThread implements Runnable
    {
        File tempFile;

        DelFileThread(File tempFile)
        {
            this.tempFile = tempFile;
        }

        public void run()
        {
            boolean succFlag = false;
            do
            {
                succFlag = this.tempFile.delete();
            }
            while (this.tempFile.exists() || !succFlag);
        }
    }

    /**
     *
     * 模板上传进度条显示监听类
     * @author
     * @version
     * @since
     */
    static class UploadProgressListener implements ProgressListener
    {
        private HttpServletRequest request = null;

        UploadProgressListener(HttpServletRequest request)
        {
            this.request = request;
        }

        public void update(long pBytesRead, long pContentLength, int pItems)
        {
            double percentage = ((double) pBytesRead / (double) pContentLength);
            // 上传的进度保存到session,以便processController.jsp使用
            request.getSession().setAttribute("uploadPercentage", percentage);
        }
    }

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

    public void setTemplateService(ITemplateService templateService)
    {
        this.templateService = templateService;
    }

    public ITemplateService getTemplateService()
    {
        return templateService;
    }

}
ZIPUtil.java
package com.coship.dhm.portalMS.common.util;

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.util.ArrayList;
import java.util.List;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import org.apache.commons.compress.archivers.ArchiveException;
import org.apache.commons.compress.archivers.ArchiveStreamFactory;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;
import org.apache.commons.compress.utils.IOUtils;

import com.xxxxxx.dhm.portalMS.common.Constants;
import com.xxxxxx.dhm.portalMS.common.DebugLogHelper;

public class ZIPUtil
{
    
    private static final int BUFFER = 8192;
    
    private static final DebugLogHelper logger = new DebugLogHelper(ZIPUtil.class);
    
    public static final String DEF_FILE_FORMAT = "zip";
    
    public static final String DEF_ENCODING = "GBK";
    
    private static void log(String msg)
    {
        
        logger.excepFuncDebugLog(msg);
        
    }
    
    /**
     *
     * 压缩工具方法,支持中文
     * @param rootPath 需要压缩的文件/目录路径
     * @param zipPath 压缩后的路径
     * @throws ArchiveException
     * @throws IOException
     * @return void
     * @exception throws
     */
    public static void file2Zip(String rootPath, String zipPath)
    {
        ZipArchiveOutputStream zos = null;
        try
        {
            zos = (ZipArchiveOutputStream)new ArchiveStreamFactory().createArchiveOutputStream(DEF_FILE_FORMAT,
                    new FileOutputStream(zipPath));
            // or new ZipArchiveOutputStream(new FileOutputStream(path))
            zos.setEncoding(DEF_ENCODING);
            File file = new File(rootPath);
            if (!file.exists())
            {
                return;
            }
            
            File[] files = null;
            if (file.isDirectory())
            {
                files = file.listFiles();
                
            }
            else
            {
                files = new File[1];
                files[0] = file;
            }
            
            zipFile(zos, files, rootPath);
        }
        catch (Exception ae)
        {
            ae.printStackTrace();
        }
        finally
        {
            if (null != zos)
            {
                try
                {
                    zos.close();
                }
                catch (IOException ioe)
                {
                    ioe.printStackTrace();
                }
            }
        }
        
    }
    
    /**
     *
     * 循环压缩
     * @param zos
     * @param files
     * @param rootPath
     * @throws IOException
     * @return void
     * @exception throws
     */
    private static void zipFile(ZipArchiveOutputStream zos, File[] files,
            String rootPath) throws IOException
    {
        ZipArchiveEntry ze = null;
        for (File f : files)
        {
            if (!f.exists())
            {
                continue;
            }
            
            ze = new ZipArchiveEntry(getEntryName(f, rootPath));// 获取每个文件相对路径,作为在ZIP中路径
            zos.putArchiveEntry(ze);
            // folder
            if (ze.isDirectory())
            {
                zos.closeArchiveEntry();
                zipFile(zos, f.listFiles(), rootPath);
            }
            // file
            else
            {
                FileInputStream fis = new FileInputStream(f);
                IOUtils.copy(fis, zos, 1024 * 10);
                fis.close();
                zos.closeArchiveEntry();
            }
        }
    }
    
    /**
     *
     * 得到文件在压缩包中的路径
     * @param f
     * @param rootPath
     * @return
     * @return String
     * @exception throws
     */
    private static String getEntryName(File f, String rootPath)
    {
        String entryName;
        String fPath = f.getAbsolutePath();
        if (fPath.indexOf(rootPath) != -1)
        {
            entryName = fPath.substring(rootPath.length() + 1);
        }
        else
        {
            entryName = f.getName();
        }
        
        if (f.isDirectory())
        {
            // "/"后缀表示entry是文件夹
            entryName += Constants.FILE_SEPARATOR.getStringValue();
        }
        
        return entryName;
    }
    
    private static String getFileName(String filePath)
    {
        
        int index = filePath.indexOf(".");
        
        return filePath.substring(0, index);
        
    }
    
    public static void zip(String sourceFilePath)
    {
        
        File fileDir = new File(sourceFilePath);
        
        if (fileDir.exists())
        {
            
            log(fileDir.getPath() + " Starting Zip ...");
            
            long startTime = System.currentTimeMillis();
            
            doZip(fileDir);
            
            long endTime = System.currentTimeMillis();
            
            long costTime = endTime - startTime;
            
            log("Zip Success!");
            
            log("use time -- " + costTime + " millsec!");
            
        }
        else
        {
            
            log("can't find the File!");
            
        }
        
    }
    
    public static void unZip(String zipFilePath)
    {
        
        File fileDir = new File(zipFilePath);
        
        if (fileDir.exists())
        {
            
            log(fileDir.getPath() + " Starting UnZip ...");
            
            long startTime = System.currentTimeMillis();
            
            doUnZip(fileDir);
            
            long endTime = System.currentTimeMillis();
            
            long costTime = endTime - startTime;
            
            log("UnZip Success!");
            
            log("use time -- " + costTime + " millsec!");
            
        }
        else
        {
            
            log("can't find the File!");
            
        }
        
    }
    
    public static void doZip(File file)
    {
        
        List<File> fileList = new ArrayList<File>();
        
        List<File> allFiles = (ArrayList<File>)searchFiles(file.getPath(),
                fileList);
        
        Object[] fileArray = allFiles.toArray();
        
        BufferedInputStream in = null;
        
        FileInputStream fis = null;
        
        ZipOutputStream zos = null;
        
        FileOutputStream fos = null;
        
        try
        {
            
            fos = new FileOutputStream(file.getParent() + File.separator
                    + file.getName() + ".zip");
            
            zos = new ZipOutputStream(new BufferedOutputStream(fos, BUFFER));
            
            zos.setLevel(9);
            
            byte[] data = new byte[BUFFER];
            
            for (int i = 0; i < fileArray.length; i++)
            {
                
                // 设置压缩文件入口entry,为被读取的文件创建压缩条目
                
                File tempFile = new File(fileArray[i].toString());
                
                String rootStr = file.getPath();
                
                String entryStr = null;
                
                // entry以相对路径的形式设置。以文件夹C:\temp例如temp\test.doc或者test.xls
                // 如果设置不当,会出现拒绝访问等错误
                
                // 分别处理单个文件/目录的entry
                
                if (rootStr.equals(tempFile.getPath()))
                {
                    
                    entryStr = tempFile.getName();
                    
                }
                else
                {
                    
                    entryStr = tempFile.getPath()
                            .substring((rootStr + File.separator).length());
                    
                }
                
                log(entryStr);
                
                ZipEntry entry = new ZipEntry(entryStr);
                
                zos.putNextEntry(entry);
                
                fis = new FileInputStream(tempFile);
                
                in = new BufferedInputStream(fis, BUFFER);
                
                int count;
                
                while ((count = in.read(data, 0, BUFFER)) != -1)
                {
                    
                    zos.write(data, 0, count);
                    
                }
                
            }
            
        }
        
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
        finally
        {
            try
            {
                
                if (fos != null)
                {
                    in.close();
                }
                if (fis != null)
                {
                    zos.close();
                }
                if (in != null)
                {
                    in.close();
                }
                if (zos != null)
                {
                    zos.close();
                }
                
            }
            catch (Exception e)
            {
                
                e.printStackTrace();
            }
        }
    }
    
    public static void doUnZip(File file)
    {
        
        try
        {
            final int BUFFER = 2048;
            
            BufferedOutputStream dest = null;
            
            FileInputStream fis = new FileInputStream(file);
            
            CheckedInputStream checksum = new CheckedInputStream(fis,
                    new Adler32());
            
            ZipInputStream zis = new ZipInputStream(new BufferedInputStream(
                    checksum));
            
            ZipEntry entry;
            
            while ((entry = zis.getNextEntry()) != null)
            {
                
                log("Extracting: " + entry);
                
                int count;
                
                byte[] data = new byte[BUFFER];
                
                log("unzip to " + getFileName(file.getPath()));
                
                FileOutputStream fos = new FileOutputStream(
                        getFileName(file.getPath()) + File.separator
                                + newDir(file, entry.getName()));
                
                dest = new BufferedOutputStream(fos, BUFFER);
                
                while ((count = zis.read(data, 0, BUFFER)) != -1)
                {
                    
                    dest.write(data, 0, count);
                    
                }
                
                dest.flush();
                
                dest.close();
            }
            
            zis.close();
            
            System.out.println("Checksum: " + checksum.getChecksum().getValue());
            
        }
        catch (Exception e)
        {
            
            e.printStackTrace();
            
        }
        
    }
    
    public static List<File> searchFiles(String sourceFilePath,
            List<File> fileList)
    {
        File fileDir = new File(sourceFilePath);
        
        if (fileDir.isDirectory())
        {
            
            File[] subfiles = fileDir.listFiles();
            
            for (int i = 0; i < subfiles.length; i++)
            {
                
                searchFiles(subfiles[i].getPath(), fileList);
                
            }
            
        }
        else
        {
            
            fileList.add(fileDir);
            
        }
        
        return fileList;
        
    }
    
    @SuppressWarnings("static-access")
    private static String newDir(File file, String entryName)
    {
        
        String rootDir = getFileName(file.getPath());
        
        log("root:" + rootDir);
        
        int index = entryName.lastIndexOf("\\");
        
        String dirStr = new File(rootDir).getParent();
        
        log(dirStr);
        
        if (index != -1)
        {
            String path = entryName.substring(0, index);
            
            log("new Dir:" + rootDir + file.separator + path);
            
            boolean b = new File(rootDir + file.separator + path).mkdirs();
            
            if (b)
            {
                logger.excepFuncDebugLog("Successfully created ...");
            }
            
            log("entry:" + entryName.substring(0, index));
            
        }
        
        else
        {
            boolean flag = new File(rootDir).mkdirs();
            
            if (flag)
            {
                logger.excepFuncDebugLog("Successfully created ...");
            }
            
            log("entry:" + entryName);
        }
        
        return entryName;
        
    }
    
    /**
     *
     * zip文件解压,支持中文
     * @param zipFile zip文件
     * @param baseDir 解压到的根目录
     * @return
     * @throws IOException
     * @return boolean
     * @exception throws
     */
    public static boolean unZipSupportChinese(File zipFile, String baseDir)
            throws IOException
    {
        DefUnZipHandler handler = new DefUnZipHandler(zipFile);
        handler.setBaseDir(baseDir);
        return handler.unZip();
    }
}

Template.java
package com.xxxxxx.dhm.portalMS.template.entity;

import java.io.Serializable;

/**
 *
 * 模板实体
 *
 * @author
 * @version
 * @since
 */
public class Template implements Serializable, Cloneable
{

    /** 序列号标识 **/
    private static final long serialVersionUID = -7621032827239794710L;

    /** 模板类型:站点模板 */
    public static final Integer SITE_TEMPLATE = 0;

    /** 模板类型:静态文件 */
    public static final Integer STATIC_FILE = 1;

    /** 模板ID **/
    private Long templateId;

    /** 模板名称 **/
    private String name;

    /** 模板类型 **/
    private Integer type;

    /** 模板别名 **/
    private String code;

    /** 模板描述 **/
    private String remark;

    /** 后缀名 **/
    private String homePage;

    /** 修改人 **/
    private Long updater;

    /** 修改时间 **/
    private String updateTime;

    /**
     * 是否为默认模板: 0.否 1.是 ,默认为0
     */
    private Integer isDefault = 0;
    /**
     * 是否已备份: 0.否 1.是 ,默认为0
     */
    private Integer isBak;

    /** 模板代码 **/
    private TemplateContent templateContent;

    /** 高标清标志 **/
//    private Integer videoType;

    // /** 栏目对象List **/
    // private List<Category> categoryList;
//    /** 模板修改开始时间,用于查询 */
//    private Date updateTimeStart;
//
//    /** 模板修改结束时间,用于查询 */
//    private Date updateTimeEnd;

    /** 判断栏目已关联模板 */
//    private Integer changeFlag;
//
    private String content;

    private String templatePath;

    /** 状态 **/
    private Integer status;

    /** 操作类型 **/
    private Integer oprType;

    /** 文件状态 **/
    private Integer fileStatus;

    /** 是否已关联栏目: 0 - 无关联; >0 - 已关联; **/
    private Integer isRelatedColumn = 0;

    /** 提供商编号 */
//    private String providerCode;

    /*** 归属地编号 */
    private String cityCode;
    
    private String cityName;


    public Long getTemplateId()
    {
        return templateId;
    }

    public void setTemplateId(Long templateId)
    {
        this.templateId = templateId;
    }

    public String getName()
    {
        return name;
    }

    public void setName(String name)
    {
        this.name = name;
    }

    public Integer getType()
    {
        return type;
    }

    public void setType(Integer type)
    {
        this.type = type;
    }

    public String getCode()
    {
        return code;
    }

    public void setCode(String code)
    {
        this.code = code;
    }

    public String getHomePage()
    {
        return homePage;
    }

    public void setHomePage(String homePage)
    {
        this.homePage = homePage;
    }

    public String getRemark()
    {
        return remark;
    }

    public void setRemark(String remark)
    {
        this.remark = remark;
    }

    public Long getUpdater()
    {
        return updater;
    }

    public void setUpdater(Long updater)
    {
        this.updater = updater;
    }

    public String getUpdateTime()
    {
        return updateTime;
    }

    public void setUpdateTime(String updateTime)
    {
        this.updateTime = updateTime;
    }

    public TemplateContent getTemplateContent()
    {
        return templateContent;
    }

    public void setTemplateContent(TemplateContent templateContent)
    {
        this.templateContent = templateContent;
    }

    public String toString()
    {
        StringBuilder builder = new StringBuilder();
        builder.append("Template [code=");
        builder.append(code);
        builder.append(", isDefault=");
        builder.append(isDefault);
        builder.append(", name=");
        builder.append(name);
        builder.append(", remark=");
        builder.append(remark);
        builder.append(", homePage=");
        builder.append(homePage);
        builder.append(", templateContent=");
        builder.append(templateContent);
        builder.append(", templateId=");
        builder.append(templateId);
        builder.append(", type=");
        builder.append(type);
        builder.append(", updateTime=");
        builder.append(updateTime);
        builder.append(", updater=");
        builder.append(updater);
//        builder.append(", videoType=");
//        builder.append(videoType);
        builder.append("]");
        return builder.toString();
    }

    public String operateDesc()
    {
        StringBuilder builder = new StringBuilder();
        builder.append("Template [code=");
        builder.append(code);
        builder.append(", isDefault=");
        builder.append(isDefault);
        builder.append(", name=");
        builder.append(name);
        builder.append(", remark=");
        builder.append(remark);
        builder.append(", templateId=");
        builder.append(templateId);
        builder.append(", type=");
        builder.append(type);
//        builder.append(", videoType=");
//        builder.append(videoType);
        builder.append(", isRelatedColumn=");
        builder.append(isRelatedColumn);
        builder.append("]");
        return builder.toString();
    }

    @Override
    public Object clone() throws CloneNotSupportedException
    {
        return super.clone();
    }

    public void setTemplatePath(String templatePath)
    {
        this.templatePath = templatePath;
    }

    public String getTemplatePath()
    {
        return templatePath;
    }

    public Integer getStatus()
    {
        return status;
    }

    public void setStatus(Integer status)
    {
        this.status = status;
    }

    public Integer getOprType()
    {
        return oprType;
    }

    public void setOprType(Integer oprType)
    {
        this.oprType = oprType;
    }

    public Integer getFileStatus()
    {
        return fileStatus;
    }

    public void setFileStatus(Integer fileStatus)
    {
        this.fileStatus = fileStatus;
    }

    public void setIsRelatedColumn(Integer isRelatedColumn)
    {
        this.isRelatedColumn = isRelatedColumn;
    }

    public Integer getIsRelatedColumn()
    {
        return isRelatedColumn;
    }

    public void setIsDefault(Integer isDefault)
    {
        this.isDefault = isDefault;
    }

    public Integer getIsDefault()
    {
        return isDefault;
    }

    public void setIsBak(Integer isBak)
    {
        this.isBak = isBak;
    }

    public Integer getIsBak()
    {
        return isBak;
    }

    public void setContent(String content)
    {
        this.content = content;
    }

    public String getContent()
    {
        return content;
    }

    public void setCityCode(String cityCode)
    {
        this.cityCode = cityCode;
    }

    public String getCityCode()
    {
        return cityCode;
    }

    public void setCityName(String cityName)
    {
        this.cityName = cityName;
    }
    public String getCityName()
    {
        return cityName;
    }

}

TemplateUtil.java


package com.coship.dhm.portalMS.template.util;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.xwork.StringUtils;

import com.xxxxxx.dhm.common.config.impl.XMLFactory;
import com.xxxxxx.dhm.portalMS.common.SerConstants;
import com.xxxxxx.dhm.portalMS.common.util.FileUtil;

/**
 * 模板操作工具类
 */
public class TemplateUtil {
    private static final String TEMPLATE_MAIN_SUFFIX_HTM = "htm";

    private static final String TEMPLATE_MAIN_SUFFIX_HTML = "html";

    /** 模板文件历史记录最多保存数量 */
    private static Integer maxHisNum = XMLFactory
            .getValueInt("templateConfig.maxHisNum");

    /**
     *
     * 重写index.htm文件
     *
     * @param templateMainPage
     *            模板入口页路径
     * @param oldStr
     *            旧字符串
     * @param newStr
     *            新字符串
     * @throws IEPGMException
     * @throws Exception
     * @return void
     * @exception throws
     */
    public static void reWriteIndexHtm(String templateMainPage, String oldStr,
            String newStr) throws Exception {
        String indexContent = FileUtil.readFileContent(templateMainPage,
                TemplateFileFTPHandle.FILE_ENCODE);
        if (StringUtils.isNotEmpty(indexContent)) {
            String indexViewContent = indexContent.replace(oldStr, newStr);
            FileUtil.stringWriteToFile(indexViewContent, templateMainPage,
                    TemplateFileFTPHandle.FILE_ENCODE);
        }
    }

    /**
     *
     * 得到模板文件根目录下的所有网页文件
     *
     * @param parentDir
     * @return
     * @return Set<String>
     * @exception throws
     */
    public static Set<String> readTemplateMainPages(String parentDir) {
        Set<String> respSet = new HashSet<String>();
        File file = new File(parentDir);
        // TODO wqb进行更改,递归进行查找所有文件夹
        if (file.exists() && file.isDirectory()) {
            File[] subFiles = file.listFiles();
            if (null != subFiles && subFiles.length > 0) {
                for (File subFile : subFiles) {
                    if (subFile.isDirectory()) {
                        String parentPath =subFile.getName()+SerConstants.FILE_SEPARATOR;
                        addDirectoryNameToSet(parentPath,subFile, respSet);
                    }
                    if (subFile.isFile()
                            && (subFile.getName().endsWith(
                                    TEMPLATE_MAIN_SUFFIX_HTM) || subFile
                                    .getName().endsWith(
                                            TEMPLATE_MAIN_SUFFIX_HTML))) {
                        respSet.add(subFile.getName());
                    }

                }
            }
        }
        return respSet;
    }

    public static void addDirectoryNameToSet(String parentPath,File directory, Set respSet) {
        try {
            if (directory == null || respSet == null)
                return;
            File[] subFiles = directory.listFiles();
            if (subFiles == null)
                return;
            for (File file : subFiles) {
                if (file.isFile()) {
                    if (file.getName().endsWith(TEMPLATE_MAIN_SUFFIX_HTM)
                            || file.getName().endsWith(
                                    TEMPLATE_MAIN_SUFFIX_HTML)) {
                        respSet.add(parentPath + file.getName());
                    }
                }
                if (file.isDirectory()) {
                    String currentPath =parentPath+file.getName()+SerConstants.FILE_SEPARATOR;
                    addDirectoryNameToSet(currentPath,file,respSet);
                }

            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    public static void delLoseDateTemplateFiles(File appZipParentDir)
            throws IOException {
        File[] subFiles = appZipParentDir.listFiles();
        if ((null != subFiles) && (subFiles.length > (maxHisNum - 1))) {
            File needDelFile = subFiles[0];
            Date needDelDate = new Date(needDelFile.lastModified());
            for (int i = 1; i < subFiles.length; i++) {
                Date fileLastModifyDate = new Date(subFiles[i].lastModified());
                if (fileLastModifyDate.before(needDelDate)) {
                    needDelFile = subFiles[i];
                    needDelDate = fileLastModifyDate;
                }
            }
            FileUtils.forceDelete(needDelFile);
        }
    }
}

FileUtil.java
package com.coship.dhm.portalMS.common.util;

import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.channels.FileChannel;
import java.util.Enumeration;

import org.apache.commons.lang.xwork.StringUtils;
import org.apache.tools.ant.util.FileUtils;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;

import com.xxxxxx.dhm.common.config.impl.XMLFactory;
import com.xxxxxx.dhm.portalMS.common.Constants;
import com.xxxxxx.dhm.portalMS.common.DebugLogHelper;
import com.xxxxxx.dhm.portalMS.common.SerConstants;
import com.xxxxxx.dhm.portalMS.exception.PortalMSException;

/**
 * FileUtil.java 文件操作工具类
 *
 * @author kanxiaohui
 */
public class FileUtil
{
    
    private static final DebugLogHelper logger = new DebugLogHelper(FileUtil.class);
    
    private static String MESSAGE = "";
    
    public static final char separator = '\\';
    
    public static final char linux_separator = '/';
    
    private static final int BUFFER_SIZE = 16 * 1024;
    
    private static final long VIRTUAL_MEMORY_SIZE = 512 * 1024 * 1024;
    
    /**
     * 读取文件的内容(文件的格式仅限.html、.css、.js)
     * @param filePath
     * @return
     * @throws IEPGMException
     * @return String
     * @throws Exception
     * @exception throws
     */
    public static String readFileContent(String filePath, String encode)
            throws Exception
    {
        BufferedInputStream bis = null;
        StringBuffer sb = new StringBuffer();
        
        try
        {
            bis = new BufferedInputStream(new FileInputStream(
                    new File(filePath)));
            byte[] buf = new byte[1024 * 10];
            int len = -1;
            while ((len = bis.read(buf)) != -1)
            {
                sb.append(new String(buf, 0, len, encode));
            }
        }
        catch (Exception e)
        {
            logger.excepFuncDebugLog("read file content error. reason:" + e);
            throw new IOException(e);
        }
        finally
        {
            try
            {
                bis.close();
            }
            catch (Exception e)
            {
                logger.excepFuncDebugLog("read file content error. reason:" + e);
                throw new Exception(e);
            }
        }
        return sb.toString();
    }
    
    /**
     * 内容输出到文件
     * @param content 内容
     * @param filePath 文件路径
     * @param encode 编码
     * @throws Exception
     * @return void
     * @exception throws
     */
    public static void stringWriteToFile(String content, String filePath,
            String encode) throws Exception
    {
        File indexTemplateFile = new File(filePath);
        if (indexTemplateFile.exists())
        {
            boolean flag = indexTemplateFile.delete();
            if (!flag)
            {
                logger.excepFuncDebugLog("delete file is failed");
            }
        }
        try
        {
            indexTemplateFile.createNewFile();
        }
        catch (IOException e1)
        {
            logger.excepFuncDebugLog("creat file is failed. filePath = " + filePath);
            throw e1;
        }
        BufferedOutputStream out = null;
        try
        {
            out = new BufferedOutputStream(new FileOutputStream(
                    indexTemplateFile));
            out.write(content.getBytes(encode));
        }
        catch (Exception e)
        {
            logger.excepFuncDebugLog("The content is written to the file failed. filePath = "
                    + filePath);
            throw e;
        }
        finally
        {
            try
            {
                out.close();
            }
            catch (Exception e)
            {
                logger.excepFuncDebugLog("Closes the output stream failure . ");
                throw (e);
            }
        }
    }
    
    /**
     * 保存文件输入流到指定目录和文件名的文件实体中
     *
     * @param destFileName 目标文件名
     * @param in 源文件输入流
     * @param destFilePath 目标文件路径
     * @throws Exception
     */
    public static void saveFile(String destFileName, InputStream in,
            String destFilePath) throws IOException
    {
        OutputStream bos = null;// 建立一个保存文件的输出流
        
        try
        {
            destFilePath = trimFilePath(destFilePath) + "/" + destFileName;
            bos = new FileOutputStream(destFilePath, false);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = in.read(buffer, 0, 8192)) != -1)
            {
                bos.write(buffer, 0, bytesRead);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (bos != null)
            {
                bos.close();
            }
            if (in != null)
            {
                in.close();
            }
        }
    }
    
    /**
     * 保存文件
     *
     * @param destFile 目标文件完整路径
     * @param in 源文件输入流
     * @throws Exception
     */
    public static void saveFile(File destFile, InputStream in)
            throws IOException
    {
        OutputStream bos = null;
        try
        {
            bos = new FileOutputStream(destFile, false);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = in.read(buffer, 0, 8192)) != -1)
            {
                bos.write(buffer, 0, bytesRead);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (bos != null)
            {
                bos.close();
            }
            if (in != null)
            {
                in.close();
            }
        }
    }
    
    /**
     * zip文件解压缩
     *
     * @param zipFileName 文件完整路径
     * @param outputDirectory 解压保存路径
     * @param isCover 是否重名覆盖
     * @throws IOException
     */
    @SuppressWarnings("unchecked")
    public static void unzip(String zipFileName, String outputDirectory,
            boolean isCover) throws IOException
    {
        logger.excepFuncDebugLog("To extract the files :" + zipFileName
                + SerConstants.COLON + outputDirectory);
        ZipFile zipFile = new ZipFile(zipFileName);
        try
        {
            Enumeration<ZipEntry> e = zipFile.getEntries();
            org.apache.tools.zip.ZipEntry zipEntry = null;
            createDirectory(outputDirectory, "");
            InputStream in = null;
            FileOutputStream out = null;
            while (e.hasMoreElements())
            {
                zipEntry = e.nextElement();
                if (zipEntry.isDirectory())
                {
                    String name = zipEntry.getName();
                    name = name.substring(0, name.length() - 1);
                    File f = new File(outputDirectory + File.separator + name);
                    if (!f.exists())
                    {
                        if (!f.mkdirs())
                        {
                            zipFile.close();
                            throw new IOException(
                                    "Failed to create the directory!");
                        }
                    }
                    
                }
                else
                {
                    String fileName = zipEntry.getName();
                    fileName = fileName.replace(separator, File.separatorChar);
                    fileName = fileName.replace(linux_separator,
                            File.separatorChar);
                    if (fileName.indexOf(File.separatorChar) != -1)
                    {
                        createDirectory(outputDirectory, getPath(fileName));
                        fileName = fileName.substring(fileName.lastIndexOf(separator) + 1,
                                fileName.length());
                    }
                    
                    File f = new File(outputDirectory + File.separator
                            + zipEntry.getName());
                    if (f.exists())
                    {
                        if (isCover)
                        {
                            // 如果要覆盖,先删除原有文件
                            FileUtils.delete(f);
                        }
                        else
                        {
                            // 如果不覆盖,不做处理
                            continue;
                        }
                        
                        // continue;
                    }
                    
                    if (!f.createNewFile())
                    {
                        zipFile.close();
                        throw new IOException("Creating file failed !");
                    }
                    try
                    {
                        in = zipFile.getInputStream(zipEntry);
                        out = new FileOutputStream(f);
                        
                        byte[] by = new byte[1024];
                        int c;
                        while ((c = in.read(by)) != -1)
                        {
                            out.write(by, 0, c);
                        }
                    }
                    catch (IOException ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        if (out != null)
                        {
                            out.close();
                        }
                        if (in != null)
                        {
                            in.close();
                        }
                    }
                }
            }
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            zipFile.close();
        }
        
    }
    
    @SuppressWarnings("unchecked")
    public static void unzipNoDir(String zipFileName, String outputDirectory,
            boolean isCover) throws IOException
    {
        logger.excepFuncDebugLog("To extract the files :" + zipFileName
                + SerConstants.COLON + outputDirectory);
        ZipFile zipFile = new ZipFile(zipFileName);
        try
        {
            Enumeration<ZipEntry> e = zipFile.getEntries();
            org.apache.tools.zip.ZipEntry zipEntry = null;
            createDirectory(outputDirectory, "");
            InputStream in = null;
            FileOutputStream out = null;
            while (e.hasMoreElements())
            {
                zipEntry = e.nextElement();
                if (zipEntry.isDirectory())
                {
                    
                }
                else
                {
                    // String fileName = zipEntry.getName();
                    String newName = zipEntry.getName()
                            .substring(zipEntry.getName().lastIndexOf('/') + 1,
                                    zipEntry.getName().length());
                    File f = new File(outputDirectory + File.separator
                            + newName);
                    if (f.exists())
                    {
                        if (isCover)
                        {
                            // 如果要覆盖,先删除原有文件
                            FileUtils.delete(f);
                        }
                        else
                        {
                            // 如果不覆盖,不做处理
                            continue;
                        }
                    }
                    
                    if (!f.createNewFile())
                    {
                        zipFile.close();
                        throw new IOException("Creating file failed !");
                    }
                    try
                    {
                        in = zipFile.getInputStream(zipEntry);
                        out = new FileOutputStream(f);
                        byte[] by = new byte[1024];
                        int c;
                        while ((c = in.read(by)) != -1)
                        {
                            out.write(by, 0, c);
                        }
                    }
                    catch (IOException ex)
                    {
                        throw ex;
                    }
                    finally
                    {
                        if (out != null)
                        {
                            out.close();
                        }
                        if (in != null)
                        {
                            in.close();
                        }
                    }
                }
            }
        }
        catch (IOException e)
        {
            throw e;
        }
        finally
        {
            zipFile.close();
        }
        
    }
    
    public static String trimFilePath(String filePath)
    {
        if (filePath == null || filePath.trim().length() == 0)
        {
            return "";
        }
        if (filePath.endsWith(String.valueOf(separator)))
        {
            filePath = filePath.substring(0, filePath.length() - 1);
        }
        return filePath;
    }
    
    private static void createDirectory(String directory, String subDirectory)
            throws IOException
    {
        String dir[];
        File fl = new File(directory);
        
        if (subDirectory.equals("") && fl.exists() != true)
        {
            if (fl.mkdirs())
            {
                throw new IOException("Creating file failed !" + directory);
            }
        }
        else if (!subDirectory.equals(""))
        {
            dir = subDirectory.replace(separator, File.separatorChar)
                    .split("\\\\");
            StringBuffer sBuffer = new StringBuffer(directory);
            for (int i = 0; i < dir.length; i++)
            {
                File subFile = new File(sBuffer.toString() + File.separator
                        + dir[i]);
                if (!subFile.exists())
                {
                    if (!subFile.mkdirs())
                    {
                        throw new IOException("Creating file failed !"
                                + subDirectory);
                    }
                }
                sBuffer.append(separator + dir[i]);
            }
            
        }
        
    }
    
    /**
     * 当文件路径包含文件名时,截取该文件所在文件夹路径
     *
     * @param fileName
     * @return
     */
    public static String getPath(String fileName)
    {
        if (fileName.lastIndexOf(File.separator) >= 0)
        {
            return fileName.substring(0, fileName.lastIndexOf(File.separator));
        }
        return fileName;
        
    }
    
    /**
     * 把字符串写入指定文件
     *
     * @param fileName
     * @param content
     */
    public static void writeStringToFile(String fileName, String content)
            throws IOException
    {
        File file = new File(fileName);
        
        if (file.exists())
        {
            FileUtils.delete(file);
        }
        // if (file.createNewFile()) {
        // throw new IOException("创建文件:" + fileName + "失败!");
        // }
        BufferedWriter writer = new BufferedWriter(new FileWriter(file));
        writer.write(content);
        writer.close();
    }
    
    /**
     * 获取某文件路径的跟路径
     *
     * @param fileName
     * @return
     */
    public static String getRootPath(String fileName)
    {
        if (fileName.lastIndexOf("/") >= 0)
        {
            return "/" + fileName.split("/")[1];
        }
        
        return fileName;
        
    }
    
    /**
     * 删除指定的文件
     * @param file
     */
    public static void deleteFile(File file) throws IOException
    {
        if (file == null || !file.exists())
        {
            return;
        }
        
        if (file.isDirectory())
        {
            deleteDirectory(file);
        }
        else
        {
            if (!file.delete())
            {
                logger.excepFuncDebugLog("deleteFile Delete file failed :"
                        + file.getAbsolutePath());
            }
        }
        
    }
    
    /**
     * 删除指定的目录
     * @param directory
     * @throws IOException
     */
    public static void deleteDirectory(File directory) throws IOException
    {
        String[] subFiles = directory.list();
        for (int i = 0; i < subFiles.length; i++)
        {
            File subFile = new File(directory.getAbsolutePath()
                    + File.separator + subFiles[i]);
            deleteFile(subFile);
        }
        if (!directory.delete())
        {
            logger.excepFuncDebugLog("deleteDirectory Delete the specified directory failed :"
                    + directory.getAbsolutePath());
        }
    }
    
    /**
     * 获取旧图片全路径
     * @param filePath 图片的路径
     * @param imageUrl 数据库中保存的图片路径
     * @return
     */
    public static String getOldResourcePath(String filePath, String imageUrl)
    {
        int imageIndex = 0;
        int imageIndex2 = 0;
        int pathIndex = 0;
        int pathIndex2 = 0;
        if (imageUrl != null && !imageUrl.equals(""))
        {
            imageIndex = imageUrl.lastIndexOf("\\");
            imageIndex2 = imageUrl.lastIndexOf("/");
            imageIndex = (imageIndex > imageIndex2 ? imageIndex : imageIndex2);
        }
        if (filePath != null && !filePath.equals(""))
        {
            pathIndex = filePath.lastIndexOf("\\");
            pathIndex2 = filePath.lastIndexOf("/");
            pathIndex = (pathIndex > pathIndex2 ? pathIndex : pathIndex2);
        }
        StringBuffer oldImagePath = new StringBuffer();
        if (pathIndex > 0)
        {
            oldImagePath.append(filePath.substring(0, pathIndex));
        }
        else
        {
            oldImagePath.append(filePath);
        }
        oldImagePath.append(File.separator);
        if (imageIndex > 0)
        {
            oldImagePath.append(imageUrl.substring(imageIndex + 1));
        }
        else
        {
            oldImagePath.append(imageUrl);
        }
        
        return oldImagePath.toString();
    }
    
    /**
     * 删除旧图片
     * @param fullFilePath 删除图片的全路径
     */
    public static void delOldResource(String fullFilePath)
    {
        if (fullFilePath != null && !fullFilePath.equals(""))
        {
            File outFile = new File(fullFilePath);
            if (outFile.exists())
            {
                if (!outFile.delete())
                {
                    logger.excepFuncDebugLog("delOldResource Remove a resource file failed :"
                            + fullFilePath);
                }
            }
        }
    }
    
    /**
     * 资源上传的处理方法
     * @param file 上传的文件实体
     * @param cover 是否重名覆盖 true -- 是,false -- 否
     * @throws PortalMSException
     */
    public static void uploadResource(File file, String path, Boolean cover)
            throws PortalMSException
    {
        if (file == null || path == null || path.equals(""))
        {
            return;
        }
        File outFile = null;
        try
        {
            outFile = new File(path);
            String pathName = FileUtil.getPath(outFile.getPath());
            FileMgrTools.createFolder(pathName);
            // 如果有同名文件
            if (outFile.exists())
            {
                // 如果选择同名覆盖
                if (cover)
                {
                    org.apache.commons.io.FileUtils.forceDelete(outFile);
                }
                else
                {// 否则退出操作
                    return;
                }
            }
            else
            {
                if (!outFile.createNewFile())
                {
                    throw new PortalMSException(
                            Constants.ERROR_CODE_NODE_RESOURCE_FIND.getLongValue(),
                            new IOException("Creating file failed !"));
                }
            }
            // 创建源文件输入流
            FileInputStream in = new FileInputStream(file);
            // 保存输入流到指定文件路径
            FileUtil.saveFile(outFile, in);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw new PortalMSException(
                    Constants.ERROR_CODE_NODE_RESOURCE_UPLOAD.getLongValue(), e);
        }
    }
    
    /**
     * 复制单个文件
     *
     * @param srcFileName 待复制的文件名
     * @param descFileName 目标文件名
     * @param overlay 如果目标文件存在,是否覆盖
     * @return 如果复制成功返回true,否则返回false
     */
    public static boolean copyFile(String srcFileName, String destFileName,
            boolean overlay)
    {
        File srcFile = new File(srcFileName);
        
        // 判断源文件是否存在
        if (!srcFile.exists())
        {
            MESSAGE = "source file:" + srcFileName + "not exist!";
            logger.excepFuncDebugLog(MESSAGE);
            return false;
        }
        else if (!srcFile.isFile())
        {
            MESSAGE = "Copy file failed ,source file:" + srcFileName
                    + "Is not a file !";
            logger.excepFuncDebugLog(MESSAGE);
            return false;
        }
        
        // 判断目标文件是否存在
        File destFile = new File(destFileName);
        if (destFile.exists())
        {
            // 如果目标文件存在并允许覆盖
            if (overlay)
            {
                // 删除已经存在的目标文件,无论目标文件是目录还是单个文件
                boolean b = new File(destFileName).delete();
                if (b)
                {
                    logger.excepFuncDebugLog("Successfully deleted ...");
                }
            }
        }
        else
        {
            // 如果目标文件所在目录不存在,则创建目录
            if (!destFile.getParentFile().exists())
            {
                // 目标文件所在目录不存在
                if (!destFile.getParentFile().mkdirs())
                {
                    // 复制文件失败:创建目标文件所在目录失败
                    return false;
                }
            }
        }
        
        // 复制文件
        int byteread = 0; // 读取的字节数
        InputStream in = null;
        OutputStream out = null;
        
        try
        {
            in = new FileInputStream(srcFile);
            out = new FileOutputStream(destFile);
            byte[] buffer = new byte[1024];
            
            while ((byteread = in.read(buffer)) != -1)
            {
                out.write(buffer, 0, byteread);
            }
            return true;
        }
        catch (FileNotFoundException e)
        {
            return false;
        }
        catch (IOException e)
        {
            return false;
        }
        finally
        {
            try
            {
                if (out != null)
                    out.close();
                
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            if (in != null)
                try
                {
                    in.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
        }
    }
    
    /**
     * 复制整个目录的内容
     *
     * @param srcDirName 待复制目录的目录名
     * @param destDirName 目标目录名
     * @param overlay 如果目标目录存在,是否覆盖
     * @return 如果复制成功返回true,否则返回false
     */
    public static boolean copyDirectory(String srcDirName, String destDirName,
            boolean overlay)
    {
        // 判断源目录是否存在
        File srcDir = new File(srcDirName);
        if (!srcDir.exists())
        {
            MESSAGE = "Copy directory failed :source directory" + srcDirName
                    + "no exist!";
            logger.excepFuncDebugLog(MESSAGE);
            return false;
        }
        else if (!srcDir.isDirectory())
        {
            MESSAGE = "Copy directory failed :" + srcDirName
                    + "Is not a directory !";
            logger.excepFuncDebugLog(MESSAGE);
            return false;
        }
        
        // 如果目标目录名不是以文件分隔符结尾,则加上文件分隔符
        if (!destDirName.endsWith(File.separator))
        {
            destDirName = destDirName + File.separator;
        }
        File destDir = new File(destDirName);
        // 如果目标文件夹存在
        if (destDir.exists())
        {
            // 如果允许覆盖则删除已存在的目标目录
            if (overlay)
            {
                try
                {
                    deleteDirectory(new File(destDirName));
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            else
            {
                MESSAGE = "Copy directory failed:destination directory "
                        + destDirName + "Already exists !";
                logger.excepFuncDebugLog(MESSAGE);
                return false;
            }
        }
        else
        {
            if (!destDir.mkdirs())
            {
                System.out.println("Copy directory failed:Create destination directory failed !");
                return false;
            }
        }
        
        boolean flag = true;
        File[] files = srcDir.listFiles();
        for (int i = 0; i < files.length; i++)
        {
            // 复制文件
            if (files[i].isFile())
            {
                flag = copyFile(files[i].getAbsolutePath(), destDirName
                        + files[i].getName(), overlay);
                if (!flag)
                    break;
            }
            else if (files[i].isDirectory())
            {
                flag = copyDirectory(files[i].getAbsolutePath(), destDirName
                        + files[i].getName(), overlay);
                if (!flag)
                    break;
            }
        }
        if (!flag)
        {
            MESSAGE = "copy directory" + srcDirName + "to" + destDirName
                    + " fail !";
            logger.excepFuncDebugLog(MESSAGE);
            return false;
        }
        else
        {
            return true;
        }
    }
    
    /**
     * 物理删除悬浮菜单图片
     * @param url
     */
    public static void deleteImageFile(String url)
    {
        String rootUrl = XMLFactory.getValueString("publish.resourceHardiskPath");
        StringBuffer generalFilePathSB = new StringBuffer();
        generalFilePathSB.append(rootUrl);
        generalFilePathSB.append(url);
        String oldImagePath = generalFilePathSB.toString();
        delOldResource(oldImagePath);
    }
    
    /**
     * 检查海报真实尺寸 1.如果尺寸为空 或不存在,则默认取其真实尺寸; 2.有尺寸则校验尺寸大小,不匹配抛出错误
     * @param file
     * @param posterType
     * @return
     */
    public static boolean checkImageFileSize(File file, String posterType)
    {
        if (StringUtils.isEmpty(posterType))
        {
            return Boolean.TRUE;
        }
        BufferedImage image = null;
        try
        {
            FileInputStream fis = new FileInputStream(file);
            image = javax.imageio.ImageIO.read(fis);
        }
        catch (Exception e)
        {
            return Boolean.FALSE;
        }
        int height = image.getHeight();
        int width = image.getWidth();
        String realSpel = width + "*" + height;
        if (posterType.indexOf(realSpel) != -1)
        {
            return Boolean.TRUE;
        }
        else
        {
            return Boolean.FALSE;
        }
        
    }
    
    /**
     * 取图片真实尺寸
     * @param file
     * @param posterType
     * @return
     */
    public static String getImageFileSize(File file)
    {
        
        BufferedImage image = null;
        try
        {
            FileInputStream fis = new FileInputStream(file);
            image = javax.imageio.ImageIO.read(fis);
        }
        catch (Exception e)
        {
            return null;
        }
        int height = image.getHeight();
        int width = image.getWidth();
        return width + "*" + height;
        
    }
    
    /**
     * @param string
     */
    public static boolean createDir(String dir)
    {
        boolean result = false;
        File f = new File(toLocalDir(dir));
        if (f.exists())
        {
            return true;
        }
        result = f.mkdir();
        if (!result)
        {
            result = f.mkdirs();
        }
        return result;
    }
    
    public static String toLocalDir(String dir)
    {
        String osName = System.getProperty("os.name").toLowerCase();
        return toLocalDir(osName, dir);
    }
    
    public static String toLocalDir(String osName, String dir)
    {
        osName = osName.toLowerCase();
        if (osName.indexOf("windows") != -1)
        {
            return dir.replace('/', '\\');
        }
        
        return dir.replace('\\', '/');
    }
    
    /**
     * Description : 镜像
     *
     * @param srcPath 来源文件
     * @param dstPath 目标文件
     * @throws Exception
     *
     */
    public static void mirror(File srcPath, File dstPath) throws Exception
    {
        mirrordelFile(srcPath, dstPath);
        copyDirectory(srcPath, dstPath);
    }
    
    // 镜像 根据目标 删除 来源的文件
    private static void mirrordelFile(File src, File dest)
    {
        if (!dest.exists())
        {
            return;
        }
        if (!src.exists())
        {
            if (dest.isDirectory())
            {
                delete(dest);
            }
            else
            {
                boolean flag = dest.delete();
                if (!flag)
                {
                    logger.excepFuncDebugLog("this file delete is failed");
                }
            }
            return;
        }
        
        if (dest.isDirectory())
        {
            if (src.isFile())
            {
                boolean flag = dest.delete();
                if (!flag)
                {
                    logger.excepFuncDebugLog("this file delete is failed");
                }
            }
            else
            {
                File[] chilefiles = dest.listFiles();
                if (null != chilefiles && chilefiles.length > 0)
                {
                    for (int i = 0; i < chilefiles.length; i++)
                    {
                        File dest2 = chilefiles[i];
                        String filename = dest2.getName();
                        String srcPath = src.getPath();
                        File src2 = new File(srcPath + File.separator
                                + filename);
                        mirrordelFile(src2, dest2);
                    }
                }
            }
        }
        else
        {
            if (src.isDirectory())
            {
                boolean flag = dest.delete();
                if (!flag)
                {
                    logger.excepFuncDebugLog("this file delete is failed");
                }
            }
        }
    }
    
    /**
     * 目录复制
     *
     * @param srcPath 源目录
     * @param dstPath 目标目录
     * @throws IOException
     */
    public static void copyDirectory(File srcPath, File dstPath)
            throws Exception
    {
        
        if (srcPath.isDirectory())
        {
            
            if (!dstPath.exists())
            {
                boolean ismkSus = dstPath.mkdirs();
                if (!ismkSus)
                {
                    logger.excepFuncDebugLog("this directory is exists:" + dstPath);
                }
            }
            
            String files[] = srcPath.list();
            
            for (int i = 0; i < files.length; i++)
            {
                File ff = new File(dstPath, files[i]);
                File srcff = new File(srcPath, files[i]);
                copyDirectory(srcff, ff);
            }
        }
        else
        {
            if (!srcPath.exists())
            {
                System.out.println("File or directory " + srcPath
                        + "does not exist.");
            }
            else
            {
                copy(srcPath, dstPath);
            }
        }
    }
    
    private static void delete(File file)
    {
        if (file.isDirectory())
        {
            File[] files = file.listFiles();
            for (int i = 0; i < files.length; i++)
            {
                if (files[i].isDirectory())
                {
                    delete(files[i]);
                }
                else
                {
                    boolean flag = files[i].delete();
                    if (!flag)
                    {
                        logger.excepFuncDebugLog("this file delete is failed");
                    }
                }
            }
            boolean flag = file.delete();
            if (!flag)
            {
                logger.excepFuncDebugLog("this file delete is failed");
            }
        }
        else
        {
            boolean flag = file.delete();
            if (!flag)
            {
                logger.excepFuncDebugLog("this file delete is failed");
            }
        }
    }
    
    /**
     * Description : 保存图片到物理路径下
     *
     * @param src
     * @param dst
     * @throws Exception
     */
    public static void copy(File src, File dst) throws Exception
    {
        InputStream srcIo = null;
        try
        {
            long srctime = src.lastModified();
            if (dst.exists())
            {
                long srcfilesize = src.length();
                long dstfilesize = dst.length();
                long dsttime = dst.lastModified();
                if (srcfilesize == dstfilesize && srctime == dsttime)
                {
                    return;
                }
            }
            srcIo = new FileInputStream(src);
            copyStream(srcIo, dst, src.length());
            boolean flag = dst.setLastModified(srctime);
            if (!flag)
            {
                logger.excepFuncDebugLog("copy file is failed");
            }
        }
        catch (FileNotFoundException e)
        {
            StringBuilder msg = new StringBuilder(src.getAbsolutePath());
            msg.append("The file does not exist !");
            logger.excepFuncDebugLog(msg.toString());
            throw e;
        }
        catch (IOException e)
        {
            StringBuilder msg = new StringBuilder(src.getAbsolutePath());
            msg.append("copy to");
            msg.append(dst.getAbsolutePath());
            msg.append("File failed !");
            logger.excepFuncDebugLog(msg.toString());
            throw e;
        }
        finally
        {
            if (null != srcIo)
            {
                srcIo.close();
            }
        }
    }
    
    private static void copyStream(InputStream src, File dst,
            final long byteCount) throws Exception
    {
        FileChannel srcChannel = null;
        FileChannel dstChannel = null;
        BufferedInputStream in = null;
        OutputStream out = null;
        FileOutputStream fOut = null;
        try
        {
            if (!dst.exists())
            {
                boolean flag = dst.createNewFile();
                if (!flag)
                {
                    logger.excepFuncDebugLog("create file is failed");
                }
            }
            if (src instanceof FileInputStream && byteCount > -1)
            {
                srcChannel = ((FileInputStream)src).getChannel();
                fOut = new FileOutputStream(dst);
                dstChannel = fOut.getChannel();
                if (VIRTUAL_MEMORY_SIZE > byteCount)
                {
                    srcChannel.transferTo(0, srcChannel.size(), dstChannel);
                }
                else
                {
                    long postion = 0;
                    while (byteCount > postion)
                    {
                        long needCopyByte = byteCount - postion;
                        if (needCopyByte > VIRTUAL_MEMORY_SIZE)
                        {
                            needCopyByte = VIRTUAL_MEMORY_SIZE;
                        }
                        postion += srcChannel.transferTo(postion,
                                needCopyByte,
                                dstChannel);
                    }
                }
            }
            else
            {
                in = new BufferedInputStream(src, BUFFER_SIZE);
                out = new BufferedOutputStream(new FileOutputStream(dst),
                        BUFFER_SIZE);
                byte[] buffer = new byte[BUFFER_SIZE];
                int len = 0;
                while ((len = in.read(buffer)) > 0)
                {
                    out.write(buffer, 0, len);
                }
            }
        }
        catch (Exception e)
        {
            logger.excepFuncDebugLog("file copy failure");
            throw e;
        }
        finally
        {
            try
            {
                if (null != dstChannel)
                {
                    dstChannel.close();
                }
            }
            catch (Exception e)
            {
                logger.excepFuncDebugLog("dstChannel close failure");
            }
            try
            {
                if (null != fOut)
                {
                    fOut.close();
                }
            }
            catch (Exception e)
            {
                logger.excepFuncDebugLog("fOut close failure");
            }
            try
            {
                if (null != srcChannel)
                {
                    srcChannel.close();
                }
            }
            catch (Exception e)
            {
                logger.excepFuncDebugLog("srcChannel close failure");
            }
            try
            {
                if (null != in)
                {
                    in.close();
                }
            }
            catch (Exception e)
            {
                logger.excepFuncDebugLog("in close failure");
            }
            try
            {
                if (null != out)
                {
                    out.close();
                }
            }
            catch (Exception e)
            {
                logger.excepFuncDebugLog("out close failure");
            }
        }
    }
    
    /**
     * 得到图片文件的BufferedImage对象(用于获取图片的相关属性: 尺寸等)
     * @param url
     * @return
     * @throws IOException
     * @return BufferedImage
     * @exception throws
     */
    public static BufferedImage fileToImage(String url) throws IOException
    {
        File file = new File(url);
        FileInputStream is = new FileInputStream(file);
        BufferedImage sourceImg = javax.imageio.ImageIO.read(is);
        return sourceImg;
    }
}


package com.coship.dhm.portalMS.common.util;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.ZipException;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;
import org.apache.log4j.Logger;


/**
 *
 * zip文件解压默认实现类
 * @author  
 * @version  
 * @since  
 */
public class DefUnZipHandler extends AbstractUnZipHandler
{

    public static final Logger logger = Logger.getLogger(DefUnZipHandler.class);
    
    public static final int DEFAULT_BUFFER_SIZE = 8 * 1024;

    private String baseDir;

    public DefUnZipHandler(File zipFile) throws IOException
    {
        super(zipFile);
    }

    public DefUnZipHandler(File zipFile, String encoding, boolean useUnicodeExtraFields) throws IOException
    {
        super(zipFile, encoding, useUnicodeExtraFields);
    }

    public DefUnZipHandler(File zipFile, String encoding) throws IOException
    {
        super(zipFile, encoding);
    }

    public DefUnZipHandler(String zipFilePath, String encoding) throws IOException
    {
        super(zipFilePath, encoding);
    }

    public DefUnZipHandler(String zipFilePath) throws IOException
    {
        super(zipFilePath);

    }

    public int copy(InputStream input, OutputStream output) throws IOException
    {
        byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
        int count = 0;
        int n = 0;
        while (-1 != (n = input.read(buffer)))
        {
            output.write(buffer, 0, n);
            count += n;
        }
        return count;
    }

    @Override
    public boolean handleFile(ZipFile zf, ZipArchiveEntry zipEntry)
    {
        boolean result = false;
        String zipEntryName = zipEntry.getName();
        InputStream content = null;
        OutputStream os = null;
        int count = 0;
        try
        {
            content = zf.getInputStream(zipEntry);
            File outFile = new File(this.getBaseDir(), zipEntryName);
            if (outFile.exists() == false)
            {
                boolean flag = outFile.createNewFile();
                if (!flag)
                {
                    logger.info("create file is failed");
                }
            }
            os = new BufferedOutputStream(new FileOutputStream(outFile));
            count = copy(content, os);
            os.flush();
        }
        catch (ZipException e)
        {
            e.printStackTrace();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (null != os)
            {
                try
                {
                    os.close();
                }
                catch (IOException e)
                {
                }
            }
        }
        if (count == zipEntry.getSize())
        {
            result = true;
        }
        return result;
    }

    @Override
    public boolean handleDirectory(ZipArchiveEntry zipEntry)
    {
        String zipEntryName = zipEntry.getName();
        File dir = new File(this.getBaseDir(), zipEntryName);
        if (dir.exists() == false)
        {
            File dirParent = dir.getParentFile();
            boolean isParmkSus = dirParent.mkdirs();
            if (!isParmkSus)
            {
                logger.info("this directory is exists:" + dirParent);
            }
            boolean ismkSus = dir.mkdir();
            if (!ismkSus)
            {
                logger.info("this directory is exists:" + dir);
            }

        }
        return dir.isDirectory() && dir.exists();
    }

    public String getBaseDir()
    {
        if (baseDir == null)
        {
            String path = super.getZipFile().getAbsolutePath();
            baseDir = path.substring(0, path.lastIndexOf("."));
            File rootDir = new File(baseDir);
            if (false == rootDir.exists())
            {
                boolean isParmkSus =  rootDir.getParentFile().mkdirs();
                if (!isParmkSus)
                {
                    logger.info("this directory is exists:" + rootDir.getParentFile());
                }
                boolean ismkSus = rootDir.mkdir();
                if (!ismkSus)
                {
                    logger.info("this directory is exists:" + rootDir);
                }
            }
            if (false == rootDir.exists())
            {
                throw new IllegalArgumentException("can't create baseDir.");
            }
        }
        return baseDir;
    }

    public void setBaseDir(String baseDir)
    {
        if (null == baseDir || baseDir.length() == 0)
        {
            throw new IllegalArgumentException("the baseDir can't be null.");
        }
        File dir = new File(baseDir);
        if (false == dir.exists())
        {
            boolean isParmkSus =  dir.getParentFile().mkdirs();
            if (!isParmkSus)
            {
                logger.info("this directory is exists:" + dir.getParentFile());
            }
            boolean ismkSus = dir.mkdir();
            if (!ismkSus)
            {
                logger.info("this directory is exists:" + dir);
            }
        }
        if (false == dir.isDirectory())
        {
            throw new IllegalArgumentException("the baseDir must be  directory.");
        }
        else
        {
            if (dir.exists() && dir.canWrite())
            {
                this.baseDir = baseDir;
            }
            else
            {
                throw new IllegalArgumentException("the baseDir is not directory or can't write.");
            }
        }
    }

    @Override
    public void handleUnZipFailed()
    {
    }

}


package com.xxxxxx.dhm.portalMS.common.util;

import java.io.File;
import java.io.IOException;
import java.util.Enumeration;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipFile;

import com.xxxxxx.dhm.portalMS.common.DebugLogHelper;

/**
 *
 * zip文件解压抽象类
 * @author  
 * @version  
 * @since  
 */
public abstract class AbstractUnZipHandler {

    private static final DebugLogHelper logger = new DebugLogHelper(AbstractUnZipHandler.class);
    
    public static final String DEF_ENCODING = "GBK";

    public static final String FOLDER_SUFFIX = "/";

    private String zipFilePath;

    private File zipFile;

    private String encoding;

    private boolean useUnicodeExtraFields;

    private ZipFile zf;

    private long start = 0;

    private long end = 0;

    private boolean global_result;
    
    public AbstractUnZipHandler(String zipFilePath) throws IOException {
        this(zipFilePath, DEF_ENCODING);
    }

    public AbstractUnZipHandler(File zipFile) throws IOException {
        this(zipFile, DEF_ENCODING);
    }

    public AbstractUnZipHandler(String zipFilePath, String encoding)
            throws IOException {
        this(new File(zipFilePath), encoding);
    }

    public AbstractUnZipHandler(File zipFile, String encoding)
            throws IOException {
        this.zipFile = zipFile;
        this.encoding = encoding;
        this.zf = new ZipFile(zipFile, encoding);
    }

    public AbstractUnZipHandler(File zipFile, String encoding,
            boolean useUnicodeExtraFields) throws IOException {
        this.zipFile = zipFile;
        this.encoding = encoding;
        this.useUnicodeExtraFields = useUnicodeExtraFields;
        this.zf = new ZipFile(zipFile, encoding, useUnicodeExtraFields);
    }

    public boolean unZip() {
        boolean result = true;
        doStrart();
        Enumeration<ZipArchiveEntry> zipEntries = zf.getEntries();
        ZipArchiveEntry zipEntry = null;
        String zipEntryName = null;
        while (zipEntries.hasMoreElements()) {
            zipEntry = zipEntries.nextElement();
            zipEntryName = zipEntry.getName();
            if (zf.canReadEntryData(zipEntry)) {
                if (zipEntryName.endsWith(FOLDER_SUFFIX)) {
                    // Directory
                    if (handleDirectory(zipEntry) == false) {
                        result = false;
                    }
                } else {
                    // File
                    if (handleFile(zf, zipEntry) == false) {
                        result = false;
                    }
                }
            } else {
                // May return false if it is set up to use encryption or a
                // compression method that hasn't been implemented yet.
                result = false;
            }
            if (result == false) {
                logger.excepFuncDebugLog("can't read zipEntry:" + zipEntryName);
                logger.excepFuncDebugLog("programe will exist.");
                break;
            }
        }
        if(null!=zf){
            try {
                zf.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            zf= null;
        }
        global_result = result;
        doEnd();
        return result;
    }

    public abstract boolean handleFile(ZipFile zf, ZipArchiveEntry zipEntry);

    public abstract boolean handleDirectory(ZipArchiveEntry zipEntry);

    public void doStrart() {
        logger.excepFuncDebugLog("start handle: " + zipFile.getAbsolutePath());
        start = System.currentTimeMillis();
    }

    public void doEnd() {
       logger.excepFuncDebugLog("global_result: "+global_result);
       logger.excepFuncDebugLog("handle over "+(global_result==true?"success":"failed")+": " + zipFile.getAbsolutePath());
       end = System.currentTimeMillis();
       logger.excepFuncDebugLog("total take: " + (end - start) + " ms.");
       if(false==global_result){
           logger.excepFuncDebugLog("unzip failure,will delete files in baseDir.");
           handleUnZipFailed();
       }
    }

    public abstract void handleUnZipFailed();

    public String getZipFilePath() {
        return zipFilePath;
    }

    public File getZipFile() {
        return zipFile;
    }

    public String getEncoding() {
        return encoding;
    }

    public boolean isUseUnicodeExtraFields() {
        return useUnicodeExtraFields;
    }

}
processController.jsp
<%@ page language="java" import="java.util.*,com.opensymphony.xwork2.ognl.OgnlValueStack" contentType = "text/html;charset=UTF-8" pageEncoding="utf-8"%>  
<%@taglib prefix="s" uri="/struts-tags"%>
<%  
    //注意上面的抬头是必须的。否则会有ajax乱码问题。   
    //从session取出uploadPercentage并送回浏览器   
    Object percent = request.getSession().getAttribute("uploadPercentage");  
    
    OgnlValueStack stack = (OgnlValueStack) request.getAttribute("struts.valueStack");

    String msg = "";  
    double d = 0;  
    if(percent==null){  
        d = 0;  
    }  
    else{  
        d = (Double)percent;  
    }  
    if(d<1){  
    //d<1代表正在上传,   
    
        msg =  (String)(stack.findValue("uploading"));
        out.write("{success:true, msg: '"+msg+"', percentage:'" + d + "', finished: false}");  
    }  
    else if(d>=1){  
        //d>1 代表上传已经结束,开始处理分析    
        msg =  (String)(stack.findValue("analysing"));
        String finished = "false";  
        double processFilePercentage = 0.0;  
        Object o = request.getSession().getAttribute("processFilePercentage");  
        if(null!=o)
        {
            processFilePercentage=(Double)o;
            if(processFilePercentage>=1)
            {  
                //processFilePercentage>1代表分析完毕。   
                request.getSession().removeAttribute("uploadPercentage");  
                request.getSession().removeAttribute("processFilePercentage");  
                //客户端判断是否结束的标志   
                finished = "true";  
            }  
        }
        
        Object upFileErrorMes = request.getSession().getAttribute("upFileErrorMes");  
        if(null == upFileErrorMes)
        {
            Object tempTemplateDir = request.getSession().getAttribute("tempTemplateDir");  
            //注意返回的数据,success代表状态   ,percentage是百分比   ,finished代表整个过程是否结束。   
            out.write("{success:true, msg: '" + tempTemplateDir + "', percentage:'" + processFilePercentage + "', finished: "+ finished + "}");
        }
        else
        {
            request.getSession().removeAttribute("upFileErrorMes");
            out.write("{success:false, msg: '"+(String)upFileErrorMes+"', percentage:'" + processFilePercentage + "', finished: "+ finished +"}");
        }
    }  
    out.flush();  
%>

   


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值