Java多文件压缩下载

 创建一个公共类ZipUtil,代码如下

/**
 * 生成压缩包
 *
 * @param pathList
 * @param fisList
 * @param zos
 * @throws IOException
 */
public static void download(List<String> pathList, List<FileInputStream> fisList, ZipOutputStream zos) throws IOException {
    for (int i = 0; i < pathList.size(); i++) {
        String path = pathList.get(i);
        FileInputStream fis = fisList.get(i);

        ZipEntry entry = new ZipEntry(path);
        zos.putNextEntry(entry);

        byte[] buf = new byte[1024];
        int len;
        while ((len = fis.read(buf)) > 0) {
            zos.write(buf, 0, len);
        }

        zos.closeEntry();
        fis.close();
    }
    zos.flush();
    zos.close();
}

 

/**
 * 压缩包内部的情况
 *
 * @return
 */
public static List<String> getPathList() {
    List<String> list = new ArrayList<>();
    //下面这些是在压缩包中的路径(第一册、测试、下级测试 都是在压缩包中才生成的)
    list.add("第一册/测试/1.txt");
    list.add("第一册/测试/2.txt");
    list.add("第2册/3.txt");
    list.add("第3册/测试/下级测试/4.txt");
    return list;
}

/**
 * 对应的文件数据(在D:\data下建了4个文件用来测试)
 *
 * @return
 * @throws FileNotFoundException
 */
public static List<FileInputStream> getFisList() throws FileNotFoundException {
    List<FileInputStream> list = new ArrayList<>();
    list.add(new FileInputStream("D:\\data\\1.txt"));
    list.add(new FileInputStream("D:\\data\\2.txt"));
    list.add(new FileInputStream("D:\\data\\3.txt"));
    list.add(new FileInputStream("D:\\data\\4.txt"));
    return list;
}

/**
 * 获取ZipOutputStream
 *
 * @return
 * @throws FileNotFoundException
 */
public static ZipOutputStream getZos() throws FileNotFoundException {
    // 实际项目中换成从HttpServletResponse中获取OutputStream
    // OutputStream os = response.getOutputStream();
    OutputStream os = new FileOutputStream("D:\\1.zip");
    ZipOutputStream zos = new ZipOutputStream(os);
    return zos;
}
/**
 * 打包压缩下载文件
 */
@RequestMapping(value = "/downloadFile/1", method = RequestMethod.GET)
public void downLoadZipFile(HttpServletResponse response) throws IOException{
    String zipName = "myfile.zip";
    response.setContentType("APPLICATION/OCTET-STREAM");
    response.setHeader("Content-Disposition","attachment; filename="+zipName);
    ZipOutputStream out = new ZipOutputStream(response.getOutputStream());
    try {
           ZipUtils.download(ZipUtils.getPathList(),ZipUtils. getFisList(), out);
        response.flushBuffer();
    } catch (Exception e) {
        e.printStackTrace();
    }finally{
        out.close();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值