文件下载并压缩为zip格式

该文章提供了一个名为ZipUtils的Java类,用于压缩和解压缩文件及目录。类中包含静态方法进行压缩和解压操作,支持指定压缩文件名和目标路径。在解压缩时,能处理目录并创建所需文件结构。文章还展示了如何在Web环境中调用这个工具类,以下载压缩文件并处理中文文件名乱码问题。
摘要由CSDN通过智能技术生成

第一:ZipUtils

package com.xxx.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

public class ZipUtils {
 
    /**
     * 压缩一个文件或者目录
     *
     * @param zipFileName 压缩后的文件名(绝对路径):
     * @param zipFilePath 需要被压缩的文件路径(绝对路径):
     * @throws Exception
     */
    public static void zip(String zipFileName, String zipFilePath) throws Exception {
        zip(zipFileName, new File(zipFilePath));
    }
 
    /**
     * @param zipFileName 压缩后的文件名及路径
     * @param zipFilePath   要被压缩的文件的输入流
     * @throws Exception
     */
    public static void zip(String zipFileName, File zipFilePath) throws Exception {
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName));
        zip(out, zipFilePath, "");
        System.out.println("zip done");
        out.close();
    }
 
    /**
     * 用于压缩整个目录或者单个文件
     *
     * @param out  源文件的输出流
     * @param f    目标压缩文件的输入流
     * @param base a
     * @throws Exception
     */
    private static void zip(ZipOutputStream out, File f, String base) throws Exception {
        System.out.println("Zipping  " + f.getName());
        if (f.isDirectory()) {
            File[] fl = f.listFiles();
            //out.putNextEntry(new ZipEntry(base+"/"));
            out.putNextEntry(new ZipEntry(base + f.getName() + "/"));
            for (int i = 0; i < fl.length; i++) {
                //zip(out,fl[i],base);
                zip(out, fl[i], base + f.getName() + "/");
            }
        } else {
            //base=base.length()==0?"":base+"/";
            out.putNextEntry(new ZipEntry(base + f.getName()));
            FileInputStream in = new FileInputStream(f);
            int len;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            in.close();
        }
    }
 
    /**
     * 解压缩
     *
     * @param zipFileName     压缩文件
     * @param outputDirectory 目标路径
     * @throws Exception
     */
    public static void unzip(String zipFileName, String outputDirectory) throws Exception {
        ZipInputStream in = new ZipInputStream(new FileInputStream(zipFileName));
        ZipEntry z;
        while ((z = in.getNextEntry()) != null) {
            System.out.println("unziping " + z.getName());
            if (z.isDirectory()) {
                String name = z.getName();
                name = name.substring(0, name.length() - 1);
                File f = new File(outputDirectory + File.separator + name);
                f.mkdir();
                System.out.println("mkdir " + outputDirectory + File.separator + name);
            } else {
                File f = new File(outputDirectory + File.separator + z.getName());
                f.createNewFile();
                FileOutputStream out = new FileOutputStream(f);
                int b;
                while ((b = in.read()) != -1){
                    out.write(b);
                }
                out.close();
            }
        }
        in.close();
    }
 
    //测试压缩文件
    public static void main(String[] args) throws Exception {
        String zipFileName="D:\\opt\\upload.zip";
        String zipFilePath="D:\\opt\\upload";
        zip(zipFileName,zipFilePath);
    }
}

第二:开始调用方法测试:

 /**
     * 下载文件,压缩为zip文件
     * @param request
     * @param response
     * @param standardUrl 压缩的路径---要压缩哪里的文件
     */
    public void zipDownload(HttpServletRequest request, HttpServletResponse response ,String standardUrl) {
        FileInputStream fis = null;
        OutputStream os = null;
        try {
            //设置页面静态文字中文编码
            response.setCharacterEncoding("UTF-8");
            //压缩目录
            String dateDir = standardUrl;
            log.info("下载文件地址为:dateDir = "+dateDir);
            //压缩名:实际工作中写定义的压缩名如系统当前时间+6位随机数(zipDirName = DateUtils.getCurrYYYYMMDD() + "_" + RandomUtils.randomByNumber(6))
            String zipDirName = "压缩包的名称";
            //定义临时压缩文件名
            String zipName = zipDirName + ".zip";
            //下面创建打zip包用的子目录
            String targetFilePath = dateDir +  File.separator;
            log.info("压缩为zip包用的子目录:targetFilePath = "+targetFilePath);
            //判断是否存在该临时目录,没有就建立
            File targetPath = new File(targetFilePath);
            if (!targetPath.exists()) {
                targetPath.mkdirs();
            }
            //压缩后的文件名路径:E:\\app_data\\upload\\temp\\batchDownload\\A2023001_检查.zip
            String downLoadFile = dateDir + zipDirName + ".zip";
            //压缩文件(调用工具类)
            ZipUtils.zip(downLoadFile, targetFilePath);
            //创建zip文件
            File file = new File(downLoadFile);
            fis = new FileInputStream(file);
            os = response.getOutputStream();

            zipName = new String(zipName.getBytes("UTF-8"), "ISO8859-1");//文件名解决中文乱码:该方法从浏览器下载中文名正常展示
            //重置,清除缓存
            response.reset();
            //附件下载且UTF-8编码
            response.setContentType("application/x-download;charset=UTF-8");
            //附件下载中文乱码问题:该方法从浏览器下载中文名正常展示
            response.addHeader("Content-Disposition", "attachment;filename=" + zipName);
            //附件下载文件长度
            response.addHeader("Content-Length", "" + (int) file.length());

            int len;
            byte[] buffer = new byte[8192];
            while ((len = fis.read(buffer)) > 0) {
                os.write(buffer, 0, len);
                os.flush();
            }
        } catch (Exception e) {
            e.getMessage();
            log.error("附件下载失败!", e);
        } finally {
            try {
                if (os != null) {
                    os.close();
                }
                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.getMessage();
                log.error("附件批量下载:打zip包IOException:{}", e);
            }
        }

    }

如果有问题请留言或者私信我,多谢

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值