Java实现Zip压缩文件并可以下载

本文介绍了如何使用Java实现将多个文件打包成Zip文件,并提供下载功能。通过org.apache.tools.zip.ZipOutputStream,创建一个压缩工具类ZipCompressor,用于压缩指定路径的文件或目录。然后在应用程序中调用该类,根据提供的文件路径生成Zip文件。最后,提供了一个下载方法,通过HttpServletRequest和HttpServletResponse响应下载请求。
摘要由CSDN通过智能技术生成

1、项目需求:将多个文件打包后,放到本地,提供下载的需求。

2、实现思路:使用org.apache.tools.zip.ZipOutputStream。

3、实现代码:

(1)做一个压缩的工具类

package com.thinkgem.jeesite.modules.data.utils;

import java.io.BufferedInputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.util.zip.CRC32;  
import java.util.zip.CheckedOutputStream;  
import java.util.zip.ZipEntry;  
import java.util.zip.ZipOutputStream;  
 
public class ZipCompressor {     
   static final int BUFFER = 8192;     
   
   private File zipFile;     
     
   public ZipCompressor(String pathName) {     
       zipFile = new File(pathName);     
   }     
   public void compress(String... pathName) {   
       ZipOutputStream out = null;     
       try {    
           FileOutputStream fileOutputStream = new FileOutputStream(zipFile);     
           CheckedOutputStream cos = new CheckedOutputStream(fileOutputStream,     
                   new CRC32());     
           out = new ZipOutputStream(cos);     
           String basedir = "";   
           for (int i=0;i<pathName.length;i++){  
               compress(new File(path

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值