Java多文件压缩

Java多文件压缩
I/O流 最全 最全 最全整理


一、使用的API:

创建zip对象

//	localFileName输出的本地文件名
ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(localFileName));

将要压缩的文件名输入

//	要压缩的单个文件名
zipOut.putNextEntry(new ZipEntry(fileName));

将文件的流,写入zipOut中

zipOut.write(buffer, 0, len);

关闭流

 zipOut.close();

二、注意点

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

二、工具类:

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());
                }
            }
        }
    }
}
  • 7
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 11
    评论
好的,我来为您解答。 首先,您可以使用 Java 中的 ZipOutputStream 类来进行多文件压缩。下面是一个简单的示例代码,演示如何将多个文件压缩成一个 ZIP 文件: ```java import java.io.*; import java.util.zip.*; public class ZipExample { public static void main(String[] args) { try { // 创建 ZIP 文件输出流 FileOutputStream fos = new FileOutputStream("example.zip"); ZipOutputStream zos = new ZipOutputStream(fos); // 待压缩文件列表 String[] fileNames = {"file1.txt", "file2.txt", "file3.txt"}; // 遍历文件列表,将每个文件加入 ZIP 文件中 for (String fileName : fileNames) { // 创建文件输入流 FileInputStream fis = new FileInputStream(fileName); ZipEntry zipEntry = new ZipEntry(fileName); zos.putNextEntry(zipEntry); // 读取文件内容并写入 ZIP 文件中 byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) > 0) { zos.write(buffer, 0, len); } // 关闭文件输入流 fis.close(); } // 关闭 ZIP 文件输出流 zos.close(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } } ``` 接下来,您可以使用 Java 中的 HttpServletResponse 类来将 ZIP 文件下载到客户端。下面是一个示例代码,演示如何实现文件下载: ```java import java.io.*; import javax.servlet.http.*; public class DownloadServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // 获取要下载的文件名 String fileName = request.getParameter("fileName"); // 设置响应头,告诉浏览器要下载的文件类型 response.setContentType("application/octet-stream"); // 设置响应头,告诉浏览器要下载的文件名 response.setHeader("Content-Disposition", "attachment;filename=" + fileName); // 读取要下载的文件并写入响应输出流 FileInputStream fis = new FileInputStream(fileName); OutputStream os = response.getOutputStream(); byte[] buffer = new byte[1024]; int len; while ((len = fis.read(buffer)) > 0) { os.write(buffer, 0, len); } os.flush(); // 关闭文件输入流和响应输出流 fis.close(); os.close(); } } ``` 在您的网站中,您可以使用一个链接来触发文件下载: ```html <a href="DownloadServlet?fileName=example.zip">Download ZIP</a> ``` 当用户点击该链接时,浏览器将向服务器发送一个 GET 请求,DownloadServlet 将读取名为 example.zip 的文件并将其写入响应输出流,浏览器将显示一个文件下载对话框,用户可以选择保存或打开该文件
评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

ha_lydms

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值