Java生成ZIP压缩包

一、使用步骤

1.引入工具

代码如下(复制粘贴即可):在util包中创建一个zip工具类=>ZipUtile


public class ZipUtile {


    /**
     * @param response
     * @param fileList 多文件列表
     * @param zipPath 压缩的文件暂存的目录,下载后会删除掉
     */
    public static void zipFiles(HttpServletResponse response, List<File> fileList, File zipPath) {
        // 1 文件压缩
        if (!zipPath.exists()) { // 判断压缩后的文件存在不,不存在则创建
            try {
                zipPath.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        FileOutputStream fileOutputStream=null;
        ZipOutputStream zipOutputStream=null;
        FileInputStream fileInputStream=null;
        try {
            fileOutputStream=new FileOutputStream(zipPath); // 实例化 FileOutputStream对象
            zipOutputStream=new ZipOutputStream(fileOutputStream); // 实例化 ZipOutputStream对象
            ZipEntry zipEntry=null; // 创建 ZipEntry对象
            for (int i=0; i<fileList.size(); i++) { // 遍历源文件数组
                fileInputStream = new FileInputStream(fileList.get(i)); // 将源文件数组中的当前文件读入FileInputStream流中
                zipEntry = new ZipEntry(fileList.get(i).getName()); // 实例化ZipEntry对象,源文件数组中的当前文件
                zipOutputStream.putNextEntry(zipEntry);
                int len; // 该变量记录每次真正读的字节个数
                byte[] buffer=new byte[1024]; // 定义每次读取的字节数组
                while ((len=fileInputStream.read(buffer)) > 0) {
                    zipOutputStream.write(buffer, 0, len);
                }
            }
            zipOutputStream.closeEntry();
            zipOutputStream.close();
            fileInputStream.close();
            fileOutputStream.close();

            // 2 文件下载
            long currentTime=System.currentTimeMillis(); // 当时时间戳
            int randomFour=(int)((Math.random()*9+1)*1000); // 4位随机数
            String fileName=String.valueOf(currentTime)+String.valueOf(randomFour)+".zip"; // 新的文件名称
            String path=zipPath.toString();

            // 设置输出的格式
            response.reset();
            response.setContentType("bin");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");

            // 循环取出流中的数据
            FileInputStream inStream=new FileInputStream(path); // 读到流中
            byte[] b = new byte[100];
            int len;
            try {
                OutputStream os=response.getOutputStream();
                response.setContentType("application/octet-stream");
                while ((len = inStream.read(b)) > 0){
                    os.write(b, 0, len);
                }
                inStream.close();
                os.flush();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {  // 3 删除压缩包
                String path=zipPath.toString();
                File zfile = new File(path);
                zfile.delete();
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}

2.实际应用

代码如下(示例):

//File()括号内是文件生成的本地路径,为E盘的test文件夹内
//文件生成名称为“静态名称学生姓名.doc”

File file1 =new File("E:\\test\\静态名称--" + student.name() + ".doc")
File file2 =new File("E:\\test\\静态名称--" + student.name() + ".doc")

List<File> fileList = new ArrayList<>();
fileList.add(file1);
fileList.add(file2);

//生成压缩包的路径,为E盘的test文件夹内
//压缩包生成名称为“静态名称学生姓名.zip”
File zPath = new File("E:\\test\\静态名称--" + student.name() + ".zip");

ZipUtile.zipFiles(response, fileList, zPath);

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值