文件夹带目录,加密,zip压缩下载

import lombok.extern.slf4j.Slf4j;
import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.springframework.util.CollectionUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author yangfeng
 * zip压缩工具
 */
@Slf4j
public class ZipUtil {

    /**
     * 下载压缩文件-不带文件夹目录(不加密)
     *
     * @param response
     * @param fileList
     * @param fileName
     * @throws Exception
     */
    public static void downloadZipFile(HttpServletResponse response, List<File> fileList, String fileName) throws Exception {
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;fileName=" +
                new String(fileName.getBytes("UTF-8"), "iso-8859-1"));

        long beginTime = System.currentTimeMillis();
        ZipOutputStream zipOutputStream = null;
        try {
            zipOutputStream = new ZipOutputStream(response.getOutputStream());
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(zipOutputStream);

            if (!CollectionUtils.isEmpty(fileList)) {
                for (File f : fileList) {
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(f));
                    zipOutputStream.putNextEntry(new ZipEntry(f.getName()));
                    int temp = 0;
                    while ((temp = bufferedInputStream.read()) != -1) {
                        bufferedOutputStream.write(temp);
                    }
                    bufferedInputStream.close();
                    bufferedOutputStream.flush();
                    response.flushBuffer();
                }
                zipOutputStream.closeEntry();
            }
            long endTime = System.currentTimeMillis();
            log.info(fileName + "压缩耗时:" + (endTime - beginTime) / 1000 + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (zipOutputStream != null) {
                zipOutputStream.close();
            }
        }
    }

    /**
     * 下载压缩文件-带文件夹目录(不加密)
     *
     * @param response
     * @param fileName
     * @throws Exception
     */
    public static void downloadAll(HttpServletResponse response, File file, String fileName) throws Exception {
        response.setContentType("application/octet-stream");
        response.addHeader("Content-Disposition", "attachment;fileName=" +
                new String(fileName.getBytes("UTF-8"), "iso-8859-1"));
        long beginTime = System.currentTimeMillis();
        ZipOutputStream zipOutputStream = null;
        try {
            zipOutputStream = new ZipOutputStream(response.getOutputStream());
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                for (File f : files) {
                    recurisionZip(zipOutputStream, f, file.getName() + File.separator);
                }
            }
            long endTime = System.currentTimeMillis();
            log.info(fileName + "压缩耗时:" + (endTime - beginTime) / 1000 + "秒");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (zipOutputStream != null) {
                zipOutputStream.close();
            }
        }
    }

    /**
     * 递归压缩文件夹目录
     *
     * @param zipOutputStream
     * @param file
     * @param baseDir
     * @throws Exception
     */
    public static void recurisionZip(ZipOutputStream zipOutputStream, File file, String baseDir) throws Exception {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File fileSec : files) {
                recurisionZip(zipOutputStream, fileSec, baseDir + file.getName() + File.separator);
            }
        } else {
            byte[] buf = new byte[1024];
            InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
            zipOutputStream.putNextEntry(new ZipEntry(baseDir + file.getName()));
            int len;
            while ((len = inputStream.read(buf)) != -1) {
                zipOutputStream.write(buf, 0, len);
            }
            inputStream.close();
        }
    }

    /**
     * 下载加密压缩-不带文件夹目录结构
     *
     * @param fileName
     * @param password
     */
    public static void encryptZip(HttpServletResponse response, ArrayList<File> files, String fileName, String password) {
        net.lingala.zip4j.io.ZipOutputStream zipOutputStream = null;
        long beginTime = System.currentTimeMillis();
        try {
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;fileName=" +
                    new String(fileName.getBytes("UTF-8"), "iso-8859-1"));

            zipOutputStream = new net.lingala.zip4j.io.ZipOutputStream(response.getOutputStream());
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(zipOutputStream);
            //设置压缩文件参数
            ZipParameters parameters = new ZipParameters();
            //设置压缩方法
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            //设置压缩级别
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            //设置压缩文件是否加密
            parameters.setEncryptFiles(true);
            //设置aes加密强度
            parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
            //设置加密方法
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
            //设置密码
            parameters.setPassword(password);
            //压缩文件,并生成压缩文件
            if (!CollectionUtils.isEmpty(files)) {
                for (File f : files) {
                    BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(f));
                    zipOutputStream.putNextEntry(f, parameters);
                    int temp = 0;
                    while ((temp = bufferedInputStream.read()) != -1) {
                        bufferedOutputStream.write(temp);
                    }
                    bufferedInputStream.close();
                    bufferedOutputStream.flush();
                    zipOutputStream.closeEntry();
                }
            }
            zipOutputStream.finish();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                zipOutputStream.close();
            } catch (Exception ex) {

            }
        }
        long endTime = System.currentTimeMillis();
        log.info(fileName + "加密压缩耗时:" + (endTime - beginTime) / 1000 + "秒");
    }

    /**
     * 下载加密压缩-带文件夹目录结构
     *
     * @param fileName
     * @param password
     */
    public static void downloadAllEncrypt(HttpServletResponse response, File file, String fileName, String password, String tempPath) throws Exception {
        long beginTime = System.currentTimeMillis();
        InputStream inputStream = null;
        OutputStream outputStream = null;
        String destFilePath = tempPath + File.separator + System.currentTimeMillis() + "_" + fileName;
        File destFile = null;
        try {
            encrypt(file, password, destFilePath);
            response.setContentType("application/octet-stream");
            response.addHeader("Content-Disposition", "attachment;fileName=" +
                    new String(fileName.getBytes("UTF-8"), "iso-8859-1"));
            destFile = new File(destFilePath);
            inputStream = new BufferedInputStream(new FileInputStream(destFile));
            outputStream = response.getOutputStream();
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                inputStream.close();
            }
            if (outputStream != null) {
                outputStream.close();
            }
        }
        if (!Objects.isNull(destFile) && destFile.exists()) {
            destFile.delete();
        }
        long endTime = System.currentTimeMillis();
        log.info(fileName + "加密压缩耗时:" + (endTime - beginTime) / 1000 + "秒");
    }

    /**
     * 加密压缩-带文件夹目录保存到本地磁盘
     *
     * @param file
     * @param password
     * @param destFile
     */
    public static void encrypt(File file, String password, String destFile) {
        try {
            //设置压缩文件参数
            ZipParameters parameters = new ZipParameters();
            ZipFile zipFile = new ZipFile(destFile);
            //设置压缩方法
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            //设置压缩级别
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            //设置压缩文件是否加密
            parameters.setEncryptFiles(true);
            //设置aes加密强度
            parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
            //设置加密方法
            parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
            //设置密码
            parameters.setPassword(password);
            if (file.isDirectory()) {
                zipFile.addFolder(file, parameters);
            }
        } catch (Exception e) {

        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值