前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Java多文件压缩

Java多文件压缩

作者头像
ha_lydms
发布2023-08-10 08:34:16
3090
发布2023-08-10 08:34:16
举报
文章被收录于专栏:学习内容

一、使用的API:

创建zip对象

代码语言:javascript
复制
//	localFileName输出的本地文件名
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(localFileName));

将要压缩的文件名输入

代码语言:javascript
复制
//	要压缩的单个文件名
zipOut.putNextEntry(new ZipEntry(fileName));

将文件的流,写入zipOut中

代码语言:javascript
复制
zipOut.write(buffer, 0, len);

关闭流

代码语言:javascript
复制
 zipOut.close();

二、注意点

  • 输入后,要关闭ZipOutputStream流,否则文件打开会失败。

二、工具类:

代码语言:javascript
复制
import lombok.extern.slf4j.Slf4j;

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


@Slf4j
public class CompressDownloadUtil {


    /**
     * 将多个文件压缩到指定输出流中
     *
     * @param files        需要压缩的文件列表
     * @param outputStream 压缩到指定的输出流
     * @author hongwei.lian
     * @date 2018年9月7日 下午3:11:59
     */
    public static void compressZip(List<File> files, OutputStream outputStream) {
        ZipOutputStream zipOutStream = null;
        try {
            //-- 包装成ZIP格式输出流
            zipOutStream = new ZipOutputStream(new BufferedOutputStream(outputStream));
            // -- 设置压缩方法
            zipOutStream.setMethod(ZipOutputStream.DEFLATED);
            //-- 将多文件循环写入压缩包
            for (int i = 0; i < files.size(); i++) {
                File file = files.get(i);
                FileInputStream filenputStream = new FileInputStream(file);
                byte[] data = new byte[(int) file.length()];
                filenputStream.read(data);
                //-- 添加ZipEntry,并ZipEntry中写入文件流,这里,加上i是防止要下载的文件有重名的导致下载失败
                zipOutStream.putNextEntry(new ZipEntry(i + file.getName()));
                zipOutStream.write(data);

                filenputStream.close();
                zipOutStream.closeEntry();
            }
        } catch (IOException e) {
            log.error("error,msg:{}", e.getMessage());
        } finally {
            try {
                if (Objects.nonNull(zipOutStream)) {
                    zipOutStream.flush();
                    zipOutStream.close();
                }
                if (Objects.nonNull(outputStream)) {
                    outputStream.close();
                }
            } catch (IOException e) {
                log.error("error,msg:{}", e.getMessage());
            }
        }
    }


    /**
     * 下载单个文件到本地
     *
     * @param localFileName 本地文件名称
     * @param is            源文件-输入流
     * @param fileName      源文件-文件名
     */
    public static void zipOneFile(String localFileName, InputStream is, String fileName) {
        ZipOutputStream zipOut = null;
        try {
            zipOut = new ZipOutputStream(new FileOutputStream(localFileName));
            zipOut.putNextEntry(new ZipEntry(fileName));
            //	输出文件
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = is.read(buffer)) > 0) {
                zipOut.write(buffer, 0, len);
            }
        } catch (IOException e) {
            log.error("获取文件失败:{}", e.getMessage());
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    log.error("关闭流失败:{}", e.getMessage());
                }
            }
        }
    }


    /**
     * 压缩多个文件到本地
     *
     * @param localFileName 本地文件名
     * @param files         File文件集合
     */
    public static void zipFiles(String localFileName, List<File> files) {
        ZipOutputStream zipOut = null;
        try {
            zipOut = new ZipOutputStream(new FileOutputStream(localFileName));


            for (File file : files) {
                FileInputStream fis = null;
                try {
                    fis = new FileInputStream(file);
                    //  单个文件名称
                    zipOut.putNextEntry(new ZipEntry(file.getName()));

                    //	输出文件
                    int len = 0;
                    byte[] buffer = new byte[1024];
                    while ((len = fis.read(buffer)) > 0) {
                        zipOut.write(buffer, 0, len);
                    }
                } catch (Exception e) {
                    log.error("压缩文件失败:{}", e.getMessage());
                } finally {
                    if (fis != null) {
                        try {
                            fis.close();
                        } catch (IOException e) {
                            log.error("关闭流失败:{}", e.getMessage());
                        }
                    }
                }
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            if (zipOut != null) {
                try {
                    zipOut.close();
                } catch (IOException e) {
                    log.error("关闭流失败:{}", e.getMessage());
                }
            }
        }
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2023-04-02,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、使用的API:
  • 二、注意点
  • 二、工具类:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档