ZIP通用工具类


import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.model.ZipParameters;
import net.lingala.zip4j.util.Zip4jConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

public class ZipUtil {

    private static Logger logger = LoggerFactory.getLogger(ZipUtil.class);

    public static boolean createFileZipByZip4j(String sourcePath, String zipPath) {
        boolean res = false;
        try {
            ZipFile zipFile = new ZipFile(zipPath);
            ZipParameters parameters = new ZipParameters();
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            zipFile.addFile(new File(sourcePath), parameters);
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    public static boolean createFolderZipByZip4j(String sourcePath, String zipPath) {
        boolean res = false;
        try {
            ZipFile zipFile = new ZipFile(zipPath);
            ZipParameters parameters = new ZipParameters();
            parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
            parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
            zipFile.addFolder(sourcePath, parameters);
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    public static boolean extract(String zipFileName, String dstPath) {
        boolean res = false;
        try {
            ZipFile zipFile = new ZipFile(zipFileName);
            zipFile.extractAll(dstPath);
            res = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return res;
    }

    /**
     * 创建ZIP文件
     *
     * @param sourcePath 文件或文件夹路径
     * @param zipPath    生成的zip文件存在路径(包括文件名)
     */
    public static boolean createZip(String sourcePath, String zipPath) {
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            fos = new FileOutputStream(zipPath);
            zos = new ZipOutputStream(fos);
            return writeZip(new File(sourcePath), "", zos);
        } catch (FileNotFoundException e) {
            logger.error("创建ZIP文件失败", e);
        } finally {
            try {
                if (zos != null) {
                    zos.close();
                }
            } catch (IOException e) {
                logger.error("创建ZIP文件失败", e);
            }
        }
        return false;
    }

    private static boolean writeZip(File file, String parentPath, ZipOutputStream zos) {
        if (file.exists()) {
            int count = 0;
            if (file.isDirectory()) {// 处理文件夹
                parentPath += file.getName() + File.separator;
                File[] files = file.listFiles();
                if (files != null) {
                    for (File f : files) {
                        writeZip(f, parentPath, zos);
                    }
                }
            } else {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(file);
                    ZipEntry ze = new ZipEntry(parentPath + file.getName());
                    zos.putNextEntry(ze);
                    byte[] content = new byte[2048];
                    int len;
                    while ((len = fis.read(content)) != -1) {
                        count = count + len;
                        zos.write(content, 0, len);
                        zos.flush();
                    }
                } catch (FileNotFoundException e) {
                    logger.error("创建ZIP文件失败", e);
                } catch (IOException e) {
                    logger.error("创建ZIP文件失败", e);
                } finally {
                    try {
                        if (fis != null) {
                            fis.close();
                        }
                    } catch (IOException e) {
                        logger.error("创建ZIP文件失败", e);
                    }
                }
            }
        } else {
            return false;
        }
        return true;
    }


    /**
     * @param zipFilename  zip的文件名
     * @param contentList  每个文件的字节流
     * @param filenameList 每个文件的文件名(如果想包含文件夹可命名为   文件夹名称/文件名.png 例:  高一(1)班/小陈.png)
     * @throws IOException
     */
    public static void writeZip(String zipFilename,
                                List<byte[]> contentList,
                                List<String> filenameList) {
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        CheckedOutputStream cos = new CheckedOutputStream(output, new CRC32());
        ZipOutputStream zos = new ZipOutputStream(cos);
        try {
            for (int i = 0; i < contentList.size(); i++) {
                byte[] content = contentList.get(i);
                String filename = filenameList.get(i);
                //构建输入流
                BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content));
                //创建文件(zip里面的文件)
                ZipEntry entry = new ZipEntry(filename);
                //放入文件
                zos.putNextEntry(entry);
                //写入文件
                copy(bis, zos);
                //关闭流
                bis.close();
            }
            zos.closeEntry();
            zos.close();
            FileUtil.writeToFile(zipFilename, output.toByteArray());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                cos.close();
                output.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }


    public static int copy(InputStream input, OutputStream output) throws IOException {
        long count = copyLarge(input, output);
        return count > 2147483647L ? -1 : (int) count;
    }

    public static long copyLarge(InputStream input, OutputStream output) throws IOException {
        byte[] buffer = new byte[4096];
        long count = 0L;

        int n;
        for (boolean var5 = false; -1 != (n = input.read(buffer)); count += (long) n) {
            output.write(buffer, 0, n);
        }
        return count;
    }


 /**
     * @param response
     * @param zipFilename  zip的文件名
     * @param contentList  每个文件的字节流
     * @param filenameList 每个文件的文件名(如果想包含文件夹可命名为   文件夹名称/文件名.png 例:  高一(1)班/小陈.png)
     * @throws IOException
     */
    public static void downloadZip(HttpServletResponse response,
                                   String zipFilename,
                                   List<byte[]> contentList,
                                   List<String> filenameList) throws IOException {
        response.reset();
        response.setContentType("application/x-msdownload;");
        response.setHeader("Content-Disposition", "attachment;filename="
                + zipFilename);

        ByteArrayOutputStream output = new ByteArrayOutputStream();
        CheckedOutputStream cos = new CheckedOutputStream(output, new CRC32());
        ZipOutputStream zos = new ZipOutputStream(cos);


        for (int i = 0; i < contentList.size(); i++) {
            byte[] content = contentList.get(i);
            String filename = filenameList.get(i);

            //构建输入流
            BufferedInputStream bis = new BufferedInputStream(new ByteArrayInputStream(content));

            //创建文件(zip里面的文件)
            ZipEntry entry = new ZipEntry(filename);
            //放入文件
            zos.putNextEntry(entry);
            //写入文件
            IOUtils.copy(bis, zos);
            //关闭流
            bis.close();
        }

        zos.closeEntry();
        zos.close();
        //设置返回信息
        response.setHeader("Content-Length", String.valueOf(output.size()));
        IOUtils.copy(new ByteArrayInputStream(output.toByteArray()), response.getOutputStream());

        //创建完压缩文件后关闭流
        cos.close();
        output.close();

    }
}

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值