java下载文件夹(其实是下载压缩文件zip)

推荐必看:https://blog.youkuaiyun.com/persistencegoing/article/details/84376427  

All rights reserved.No part of this article may be reproduced or distributed by any means,or stored in a database or retrieval system,without the prior written permission of persistenceGoing author
 

第一步把多个文件夹生成压缩文件

package com.shutang.util;

import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.CRC32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * 压缩类
 * @author xrj
 * @date 2019/10/31
 */
public class ZipCompressor {

    static final int BUFFER = 8192;

    /**
     * 压缩的文件夹
     */
    private File zipFile;

    public ZipCompressor(String pathName) {
        zipFile = new File(pathName);
    }


    /**
     * 遍历需要压缩文件集合
     * @param pathName
     * @throws IOException
     */
    public void compress(String... pathName) throws IOException {
        ZipOutputStream out =null;
        FileOutputStream fileOutputStream=null;
        CheckedOutputStream cos=null;
        try {
            fileOutputStream = new FileOutputStream(zipFile);
            cos = new CheckedOutputStream(fileOutputStream,new CRC32());
            out = new ZipOutputStream(cos);
            String basedir = "";
            for (int i=0;i<pathName.length;i++){
                compress(new File(pathName[i]), out, basedir);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(out!=null){
                out.close();
            }
            if(fileOutputStream!=null){
                fileOutputStream.close();
            }
            if(cos!=null){
                cos.close();
            }
        }
    }


    /**
     * 压缩
     * @param file
     * @param out
     * @param basedir
     */
    private void compress(File file, ZipOutputStream out, String basedir) throws IOException {
        // 判断是目录还是文件
        if (file.isDirectory()) {
            this.compressDirectory(file, out, basedir);
        } else {
            this.compressFile(file, out, basedir);
        }
    }

    /**
     * 压缩一个目录
     * */
    private void compressDirectory(File dir, ZipOutputStream out, String basedir) throws IOException {
        if (!dir.exists()){
            return;
        }
        File[] files = dir.listFiles();
        for (int i = 0; i < files.length; i++) {
            // 递归
            compress(files[i], out, basedir + dir.getName() + "/");
        }
    }

    /**
     * 压缩一个文件
     *
     * */
    private void compressFile(File file, ZipOutputStream out, String basedir) throws IOException {
        if (!file.exists()) {
            return;
        }
        BufferedInputStream bis =null;
        try {
            bis = new BufferedInputStream(new FileInputStream(file));
            ZipEntry entry = new ZipEntry(basedir + file.getName());
            out.putNextEntry(entry);
            int count;
            byte[] data = new byte[BUFFER];
            while ((count = bis.read(data, 0, BUFFER)) != -1) {
                out.write(data, 0, count);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }finally {
            if(bis!=null){
                bis.close();
            }
        }
    }


    /**
     * 生成压缩文件
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        //压缩文件生成的路径
        ZipCompressor zc = new ZipCompressor("D:/CloudMusic/resource.zip");
        List<String> list=new ArrayList<>();
        //随便新建几个文件
        list.add("D:/CloudMusic/1.doc");
        list.add("D:/CloudMusic/2.xls");
        list.add("D:/CloudMusic/3.txt");
        //图片文件夹
        list.add("D:/CloudMusic/img/");
        String[] strings = new String[list.size()];
        list.toArray(strings);
        zc.compress(strings);
    }


}

 

 

 

第二步    工具类zip下载方法

/**
 * 下载压缩包
 * @param file
 * @param response
 * @return
 */
public static HttpServletResponse downloadZip(File file,HttpServletResponse response) {
    InputStream fis = null;
    OutputStream toClient = null;
    try {
        // 以流的形式下载文件。
         fis = new BufferedInputStream(new FileInputStream(file.getPath()));
        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        // 清空response
        response.reset();
         toClient = new BufferedOutputStream(response.getOutputStream());
        response.setContentType("application/octet-stream");

        //如果输出的是中文名的文件,在此处就要用URLEncoder.encode方法进行处理
        response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
        toClient.write(buffer);
        toClient.flush();
    } catch (IOException ex) {
        ex.printStackTrace();
    }finally{
        try {
            File f = new File(file.getPath());
            f.delete();
           if(fis!=null){
               fis.close();
           }
           if(toClient!=null){
               toClient.close();
           }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    return response;
}

 

第三步controller调用

/**
 *  下载
 * @return
 */
@RequestMapping(value = "/down.do")
public void down(HttpServletResponse response){
    
String name="D:/CloudMusic/"+System.currentTimeMillis()+".zip";
ZipCompressor zc = new ZipCompressor(name);
List<String> list=new ArrayList<>();
list.add("D:/CloudMusic/1.doc");
list.add("D:/CloudMusic/2.xls");
list.add("D:/CloudMusic/3.txt");
list.add("D:/CloudMusic/img/");
String[] strings = new String[list.size()];
list.toArray(strings);
File file=null;
try {
   zc.compress(strings);
   file=new File(name);
   LoadUtils.downloadZip(file,response);
} catch (IOException e) {
   e.printStackTrace();
}finally {
   if(file!=null){
      file.delete();
   }
}
}

 

工作中使用的话,压缩文件名用时间戳,用完记得删除本地文件。

 

博主强烈推荐:https://blog.youkuaiyun.com/persistencegoing/article/details/84376427

希望大家关注我一波,防止以后迷路,有需要的可以加群讨论互相学习java ,学习路线探讨,经验分享与java求职  

群号:721 515 304

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值