JAVA 超详细 将文件夹目录打包为 ZIP 压缩包并下载

1.需求:需要给服务端文件夹打包成zip文件,然后下载,我这里提供control层代码和工具类。

2.代码

1)cotrol层

@ApiOperation(value = "打包文件并下载zip文件")
    @GetMapping(value = "/downloadZip")
    public void downloadZip(HttpServletResponse response) {
        String zipPath = "C:/Users/zhangying/Desktop/test";
        File file = new File(zipPath);//创建指定目录和文件名称的文件对象
        try {
            FolderToZipUtil.zip(zipPath,response);
        } catch (Exception e) {
           e.printStackTrace();
        }
    }

2)工具类,这里提供打包工具类和流关闭工具类

package cn.o.microfront.server.utils;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @program: microfront-server
 * @description: 文件夹压缩为zip文件
 * @author: zhangy
 * @create: 2021-04-01 09:43
 */
public class FolderToZipUtil {

    public static void zip(String sourceFileName, HttpServletResponse response){
        ZipOutputStream out = null;
        BufferedOutputStream bos = null;
        try {
            //将zip以流的形式输出到前台
            response.setHeader("content-type", "application/octet-stream");
            response.setCharacterEncoding("utf-8");
            // 设置浏览器响应头对应的Content-disposition
            //参数中 testZip 为压缩包文件名,尾部的.zip 为文件后缀
            response.setHeader("Content-disposition",
                    "attachment;filename=" + new String("ocn".getBytes("gbk"), "iso8859-1")+".zip");
            //创建zip输出流
            out = new ZipOutputStream(response.getOutputStream());
            //创建缓冲输出流
            bos = new BufferedOutputStream(out);
            File sourceFile = new File(sourceFileName);
            //调用压缩函数
            compress(out, bos, sourceFile, sourceFile.getName());
            out.flush();

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOCloseUtil.close(bos, out);
        }
    }

    /**
     * 文件压缩
     * @param out
     * @param bos
     * @param sourceFile
     * @param base
     */
    public static void compress(ZipOutputStream out, BufferedOutputStream bos, File sourceFile, String base){
        FileInputStream fos = null;
        BufferedInputStream bis = null;
        try {
            //如果路径为目录(文件夹)
            if (sourceFile.isDirectory()) {
                //取出文件夹中的文件(或子文件夹)
                File[] flist = sourceFile.listFiles();
                if (flist.length == 0) {//如果文件夹为空,则只需在目的地zip文件中写入一个目录进入点
                    out.putNextEntry(new ZipEntry(base + "/"));
                } else {//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
                    for (int i = 0; i < flist.length; i++) {
                        compress(out, bos, flist[i], base + "/" + flist[i].getName());
                    }
                }
            } else {//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入zip文件中
                out.putNextEntry(new ZipEntry(base));
                fos = new FileInputStream(sourceFile);
                bis = new BufferedInputStream(fos);

                int tag;
                //将源文件写入到zip文件中
                while ((tag = bis.read()) != -1) {
                    out.write(tag);
                }
                bis.close();
                fos.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            IOCloseUtil.close(bis,fos);
        }
    }
}

 

package cn.o.microfront.server.utils;

import java.io.Closeable;
import java.io.IOException;

/**
 * @program: microfront-server
 * @description: IO流关闭工具Utils
 * @author: zhangy
 * @create: 2021-04-01 09:28
 */
public class IOCloseUtil {

    /**
     *   IO流关闭工具类
     */
    public static void close(Closeable... io) {
        for (Closeable temp : io) {
            try {
                if (null != temp)
                    temp.close();
            } catch (IOException e) {
                System.out.println("" + e.getMessage());
            }
        }
    }

    public static <T extends Closeable> void closeAll(T... io) {
        for (Closeable temp : io) {
            try {
                if (null != temp)
                    temp.close();
            } catch (IOException e) {
                System.out.println("" + e.getMessage());
            }
        }

    }
}

 3.测试

1)使用psotman测试,测试是可以给文件打包成zip文件并下载到指定目录。

评论 11
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值