Newer
Older
casic-metering-biz-xichang / casic-metering-common / src / main / java / com / casic / missiles / utils / ZipUtils.java
chaizhuang on 15 Mar 2024 5 KB zip打印新增附件
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.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
     * @return
     * @throws Exception
     */
    private static void doCreateZipFile(File[] files, String fileSaveRootPath, ZipOutputStream out, String dir) throws Exception {
        //遍历jsonArray列表获取所有JSONObject对象
        for (int i = 0; i < files.length; i++) {
            //以论文标题为每个文件命名
            if (files[i].isFile()) {
                FileInputStream fis = new FileInputStream(fileSaveRootPath + File.separator + files[i].getName());
                out.putNextEntry(new ZipEntry(dir + files[i].getName()));
                //写入压缩包
                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();
                // 需要保留原来的文件结构时,需要对空文件夹进行处理
                // 空文件夹的处理
                out.putNextEntry(new ZipEntry(files[i].getName() + "/"));
                // 没有文件,不需要文件的copy
                doCreateZipFile(childFiles, files[i].getAbsolutePath(), out, files[i].getName() + File.separator);
                out.closeEntry();//关闭当前zip条目读取下一条
            }
        }
    }

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