批量压缩zip文件


import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import com.infoservice.mvc.context.ActionContext;
import com.svw.domssk.actions.hicrecord.HicRecordAction;

/**
 * <p>
 * ClassName: ZipFileUtil
 * </p>
 * <p>
 * Description: TODO
 * </p>
 * <p>
 * Author: yfc
 * </p>
 * <p>
 * Date: 2018-2-1
 * </p>
 */
public class ZipFileUtil {
    /**
     * <p>
     * Field k:定义递归次数变量
     * </p>
     */
    static int k = 1;
    /**
     * <p>
     * Field logger: TODO
     * </p>
     */
    private static Logger logger = Logger.getLogger(HicRecordAction.class);

    /**
     * <p>
     * Description: 压缩
     * </p>
     * 
     * @param zipFileName ZIP文件名包含全路径
     * @param fileName 压缩的文件名
     * @param delpath 根目录
     * @param files 压缩的文件
     */
    public static void getDownload(String zipFileName, String fileName, String delpath, File... files) {
        ActionContext act = ActionContext.getContext();
        HttpServletResponse response = act.getResponse().getHttpResponse();
        try {
            //获取压缩后的文件
            ZipFileUtil.zip(zipFileName, files);
            //下载压缩后的文件
            DownloadUtil.downloadFile(fileName, new File(zipFileName), response);
            logger.info("下载完成-----删除临时文件");
            ZipFileUtil.delFolder(delpath);
            ZipFileUtil.delFolder(zipFileName);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * <p>
     * Description: 压缩指定的单个或多个文件,如果是目录,则遍历目录下所有文件进行压缩
     * </p>
     * 
     * @param zipFileName ZIP文件名包含全路径
     * @param files 压缩的文件
     * @return null
     */
    public static HttpServletResponse zip(String zipFileName, File... files) {
        logger.info("压缩: " + zipFileName);
        ZipOutputStream out = null;
        try {
            createDir(zipFileName);
            out = new ZipOutputStream(new FileOutputStream(zipFileName));
            out.setEncoding("gbk");
            for (int i = 0; i < files.length; i++) {
                if (null != files[i]) {
                    zip(out, files[i], files[i].getName());
                }
            }
            out.close(); // 输出流关闭
            logger.info("压缩完成-----下载临时文件");
            return null;
        } catch (Exception e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

    /**
     * 执行压缩
     * 
     * @param out ZIP输入流new File("D:\\skoda_doms\\temp"
     * @param f 被压缩的文件
     * @param base 被压缩的文件名
     */
    private static void zip(ZipOutputStream out, File f, String base) { // 方法重载
        try {
            if (f.isDirectory()) { //压缩目录
                try {
                    File[] fl = f.listFiles();
                    if (fl.length == 0) {
                        out.putNextEntry(new ZipEntry(base + "/")); // 创建zip实体
                        logger.info(base + "/");
                    }
                    for (int i = 0; i < fl.length; i++) {
                        zip(out, fl[i], base + "/" + fl[i].getName()); // 递归遍历子文件夹
                    }
                    k++;
                } catch (IOException e) {
                    logger.error(e.getMessage());
                    e.printStackTrace();
                }
            } else { //压缩单个文件
                logger.info(base);
                out.putNextEntry(new ZipEntry(base)); // 创建zip实体
                FileInputStream in = new FileInputStream(f);
                BufferedInputStream bi = new BufferedInputStream(in);
                int b;
                while ((b = bi.read()) != -1) {
                    out.write(b); // 将字节流写入当前zip目录
                }
                out.closeEntry(); //关闭zip实体
                in.close(); // 输入流关闭
            }

        } catch (IOException e) {
            logger.error(e.getMessage());
            e.printStackTrace();
        }
    }

    /**
     * 目录不存在时,先创建目录
     * 
     * @param zipFileName 压缩后的文件名
     */
    private static void createDir(String zipFileName) {
        String filePath = StringUtils.substringBeforeLast(zipFileName, "/");
        File targetFile = new File(filePath);
        if (!targetFile.exists()) { //目录不存在时,先创建目录
            targetFile.mkdirs();
        }
    }

    /**
     * <p>
     * Description: TODO
     * </p>
     * 
     * @param file 需要打包的文件
     * @param response 响应
     * @return response
     */
    public static HttpServletResponse downloadZip(File file, HttpServletResponse response) {
        //以流的形式下载文件
        try {
            InputStream fis = new BufferedInputStream(new FileInputStream(file.getPath()));
            byte[] buffer = new byte[fis.available()];
            fis.read(buffer);
            fis.close();

            //清空response
            response.reset();

            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");

            //如果输出的中文名的文件,此处要用URLEncoder.encode方法进行处理
            response.setHeader("Content-Disposition",
                "attachment;filename=" + URLEncoder.encode(SysUtil.filterHeather(file.getName()), "UTF-8"));
            toClient.write(buffer);
            toClient.flush();
            toClient.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            File f = new File(file.getPath());
            f.delete();
        }
        return response;
    }

    /***
     * 删除指定文件夹下所有文件
     * 
     * @param path 文件夹完整绝对路径
     * @return 文件
     */
    public static boolean delAllFile(String path) {
        boolean flag = false;
        File file = new File(path);
        if (!file.exists()) {
            return flag;
        }
        if (!file.isDirectory()) {
            return flag;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                temp.delete();
            }
            if (temp.isDirectory()) {
                // 先删除文件夹里面的文件  
                delAllFile(path + "/" + tempList[i]);
                // 再删除空文件夹  
                delFolder(path + "/" + tempList[i]);
                flag = true;
            }
        }
        return flag;
    }

    /***
     * 删除文件夹
     * 
     * @param folderPath 文件夹完整绝对路径
     */
    public static void delFolder(String folderPath) {
        try {
            delAllFile(folderPath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

阅读更多
个人分类: Java后台
上一篇JDBC
下一篇文件下载
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭