Newer
Older
casic-metering-biz-xichang / casic-metering-common / src / main / java / com / casic / missiles / utils / ZipUtils.java
package com.casic.missiles.utils;


import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author zhouxuan
 * @since 2019/4/19
 */
public class ZipUtils {


    public static void batchDownloadFiles(String rootFileName, HttpServletResponse response, String localFileDir) {
        FileInputStream is = null;
        BufferedOutputStream out = null;
        String rootFilePath = rootFileName + ".zip";
        try {
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/zip;charset=utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(rootFilePath, StandardCharsets.UTF_8.name()));
            response.setHeader("Access-Control-Allow-Origin", "*");
            System.out.println(response.getHeader("Content-Disposition"));
            rootFilePath = createZipFile(localFileDir, rootFileName, rootFilePath);
            //开始下载
            is = new FileInputStream(new File(rootFilePath));
            out = new BufferedOutputStream(response.getOutputStream());
            byte[] buff = new byte[1024];
            int len = 0;
            while ((len = is.read(buff, 0, buff.length)) != -1) {
                out.write(buff, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //删除文件
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (out != null) {
                try {
                    out.close();
                    if (StringUtils.isNotEmpty(rootFilePath)) {
                        new ZipUtils().zipFileDeletor(rootFilePath);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 批量打包
     *
     * @param downloadPath 项目根目录
     * @return tempDir 文件保存绝对路径
     */
    public static String createZipFile(String downloadPath, String tempDir, String papersZipName) {
        ZipOutputStream out = null;
        try {
            //zip文件保存路径
            String zipPath = downloadPath + papersZipName;
            String fileSaveRootPath = downloadPath + tempDir;
            File file = new File(fileSaveRootPath);
            File[] files = file.listFiles();
            out = new ZipOutputStream(new FileOutputStream(zipPath));
            //遍历jsonArray列表获取所有JSONObject对象
            doCreateZipFile(files, fileSaveRootPath, out, "");
            out.close();
            out.flush();
            return zipPath;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }


    /**
     * 递归调用
     *
     * @param files
     * @param fileSaveRootPath
     * @param out
     * @param parentDir
     * @return
     * @throws Exception
     */
    private static void doCreateZipFile(File[] files, String fileSaveRootPath, ZipOutputStream out, String parentDir) throws Exception {
        for (int i = 0; i < files.length; i++) {
            String currentFilePath = fileSaveRootPath + File.separator + files[i].getName();

            if (files[i].isFile()) {
                FileInputStream fis = new FileInputStream(currentFilePath);
                String entryName = parentDir + files[i].getName();
                out.putNextEntry(new ZipEntry(entryName));
                int len;
                byte[] buffer = new byte[1024];
                while ((len = fis.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                out.closeEntry();
                fis.close();
            } else if (files[i].isDirectory()) {
                File[] childFiles = files[i].listFiles();
                String dirName = parentDir + files[i].getName() + File.separator;
                out.putNextEntry(new ZipEntry(dirName));
                out.closeEntry(); // 关闭空目录条目

                // 递归处理子目录
                doCreateZipFile(childFiles, files[i].getAbsolutePath(), out, dirName);
            }
        }
    }

    /**
     * 批量打包
     *
     * @param zipPath zip路径
     * @return zip文件保存绝对路径
     */
    public void zipFileDeletor(String zipPath) {
        try {
            File zipFile = new File(zipPath);
            zipFile.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}