Java代码如何对Excel文件进行zip压缩

news2024/9/29 15:31:31

1:新建 ZipUtils 工具类

package com.ly.cloud.datacollection.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ZipUtils {
	private static final int BUFFER_SIZE = 10 * 1024;

   /**
    * 
    * @param fileList 多文件列表
    * @param zipPath 压缩文件临时目录
    * @return
    */
    public static Boolean zipFiles(List<File> fileList, File zipPath) {
    	boolean flag = true;
        // 1 文件压缩
        if (!zipPath.exists()) { // 判断压缩后的文件存在不,不存在则创建
            try {
                zipPath.createNewFile();
            } catch (IOException e) {
            	flag=false;
                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("("+i+")"+fileList.get(i).getName()); // 实例化ZipEntry对象,源文件数组中的当前文件
                zipOutputStream.putNextEntry(zipEntry);
                int len; // 该变量记录每次真正读的字节个数
                byte[] buffer=new byte[BUFFER_SIZE]; // 定义每次读取的字节数组
                while ((len=fileInputStream.read(buffer)) != -1) {
                    zipOutputStream.write(buffer, 0, len);
                }
            }
            zipOutputStream.closeEntry();
            zipOutputStream.close();
            fileInputStream.close();
            fileOutputStream.close();

        } catch (IOException e) {
        	flag=false;
            e.printStackTrace();
        } finally {
            try {  
            	fileInputStream.close();
            	zipOutputStream.close();
            	fileOutputStream.close();
            } catch (Exception e){
            	flag=false;
                e.printStackTrace();
            }
        }
		return flag;
    }
   

    /**
     * @param srcDir           压缩文件夹路径
     * @param keepDirStructure 是否保留原来的目录结构,
     *                         true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @param response 
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String[] srcDir, String outDir,
                             boolean keepDirStructure, HttpServletResponse response) throws RuntimeException, Exception {
        // 设置输出的格式
        response.reset();
        response.setContentType("bin");
        outDir = URLEncoder.encode(outDir,"UTF-8");
        response.addHeader("Content-Disposition","attachment;filename=" + outDir);
        OutputStream out = response.getOutputStream();
        response.setContentType("application/octet-stream");
        ZipOutputStream zos = null;
        try {
            zos = new ZipOutputStream(out);
            List<File> sourceFileList = new ArrayList<File>();
            for (String dir : srcDir) {
                File sourceFile = new File(dir);
                sourceFileList.add(sourceFile);
            }
            compress(sourceFileList, zos, keepDirStructure);
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } 
       finally {
        	if (zos != null) {
        		try {
        			zos.close();
        			out.close();
        		} catch (IOException e) {
        			e.printStackTrace();
        		}
        	}
		}
    }
    /**
     * @param srcDir           压缩文件夹路径
     * @param keepDirStructure 是否保留原来的目录结构,
     *                         true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @param response 
     * @throws RuntimeException 压缩失败会抛出运行时异常
     */
    public static void toZip(String[] srcDir, String outDir,
                             boolean keepDirStructure) throws RuntimeException, Exception {
        // 设置输出的格式
        //outDir = URLEncoder.encode(outDir,"UTF-8");
    	long start= System.currentTimeMillis();
        FileOutputStream out=null;
        ZipOutputStream zos = null;
        try {
        	out=new FileOutputStream(outDir); // 实例化 FileOutputStream对象
            zos = new ZipOutputStream(out);
            List<File> sourceFileList = new ArrayList<File>();
            for (String dir : srcDir) {
                File sourceFile = new File(dir);
                sourceFileList.add(sourceFile);
            }
            compress(sourceFileList, zos, keepDirStructure);
        } catch (Exception e) {
            throw new RuntimeException("zip error from ZipUtils", e);
        } 
       finally {
        	if (zos != null) {
        		try {
        			zos.close();
        			out.close();
        			log.info(outDir+"压缩完成");
        			printInfo(start);
        		} catch (IOException e) {
        			e.printStackTrace();
        		}
        	}
		}
    }

    /**
     * 递归压缩方法
     *
     * @param sourceFile       源文件
     * @param zos              zip输出流
     * @param name             压缩后的名称
     * @param keepDirStructure 是否保留原来的目录结构,
     *                         true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception 异常
     */
    private static void compress(File sourceFile, ZipOutputStream zos,
                                 String name, boolean keepDirStructure) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        recursion(sourceFile, zos, name, keepDirStructure, buf);
    }

    /**
     *
     * @param sourceFileList    源文件列表
     * @param zos               zip输出流
     * @param keepDirStructure  是否保留原来的目录结构,
     *                          true:保留目录结构;
     *                          false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @throws Exception        异常
     */
    private static void compress(List<File> sourceFileList,
                                 ZipOutputStream zos, boolean keepDirStructure) throws Exception {
        byte[] buf = new byte[BUFFER_SIZE];
        for (File sourceFile : sourceFileList) {
            String name = sourceFile.getName();
            recursion(sourceFile, zos, name, keepDirStructure, buf);
        }
    }

    /**
     *
     * @param sourceFile       源文件
     * @param zos              zip输出流
     * @param name             文件名
     * @param keepDirStructure 否保留原来的目录结构,
     *                         true:保留目录结构;
     *                         false:所有文件跑到压缩包根目录下(注意:不保留目录结构可能会出现同名文件,会压缩失败)
     * @param buf              字节数组
     * @throws Exception       异常
     */
    private static void recursion(File sourceFile, ZipOutputStream zos, String name, boolean keepDirStructure, byte[] buf) {
        if (sourceFile.isFile()) {
        	FileInputStream in=null;
            try {
            	in = new FileInputStream(sourceFile);
				zos.putNextEntry(new ZipEntry(name));
				int len;
				while ((len = in.read(buf)) != -1) {
					zos.write(buf, 0, len);
				}
				zos.closeEntry();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}finally {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
        } else {
            File[] listFiles = sourceFile.listFiles();
            if (listFiles == null || listFiles.length == 0) {
                if (keepDirStructure) {
                    try {
						zos.putNextEntry(new ZipEntry(name + "/"));
						zos.closeEntry();
					} catch (IOException e) {
						e.printStackTrace();
					}
                }
            } else {
                for (File file : listFiles) {
                    if (keepDirStructure) {
                        try {
							compress(file, zos, name + "/" + file.getName(),
							        true);
						} catch (Exception e) {
							e.printStackTrace();
						}
                    } else {
                        try {
							compress(file, zos, file.getName(), false);
						} catch (Exception e) {
							e.printStackTrace();
						}
                    }
                }
            }
        }
    }
    public static int deleteFile(File file) {
        //判断是否存在此文件
    	int count=0;
        if (file.exists()) {
            //判断是否是文件夹
            if (file.isDirectory()) {
                File[] files = file.listFiles();
                //判断文件夹里是否有文件
                if (files.length >= 1) {
                    //遍历文件夹里所有子文件
                    for (File file1 : files) {
                        //是文件,直接删除
                        if (file1.isFile()) {
                        	count++;
                            file1.delete();
                        } else {
                            //是文件夹,递归
                        	count++;
                        	deleteFile(file1);
                        }
                    }
                    //file此时已经是空文件夹
                    file.delete();
                } else {
                    //是空文件夹,直接删除
                    file.delete();
                }
            } else {
                //是文件,直接删除
                file.delete();
            }
        } else {
        }
		return count;
    }
    

public static void downloadFile(String path, File file, String outDir, HttpServletResponse response){
        OutputStream os = null;
        FileInputStream fis=null;
        try {
        	fis = new FileInputStream(file);
            // 取得输出流
            os = response.getOutputStream();
            //String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
            outDir = URLEncoder.encode(outDir,"UTF-8");
            response.addHeader("Content-Disposition","attachment;filename=" + outDir);
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Length", String.valueOf(file.length()));
            //response.setHeader("Content-Disposition", "attachment;filename="+ outDir);
            //response.setHeader("Content-Disposition", "attachment;filename="+ new String(file.getName().getBytes("utf-8"),"ISO8859-1"));
			/*
			 * int len; // 该变量记录每次真正读的字节个数 byte[] buffer=new byte[BUFFER_SIZE]; //
			 * 定义每次读取的字节数组 while ((len=fis.read(buffer)) != -1) { os.write(buffer, 0, len);
			 * }
			 */
            
            WritableByteChannel writableByteChannel = Channels.newChannel(os);
            FileChannel fileChannel = fis.getChannel();
            	ByteBuffer buffer=ByteBuffer.allocate(BUFFER_SIZE);
            	long total=0L;
            	int len=0;
				while((len=fileChannel.read(buffer))!=-1){
					total=total+len;
						buffer.flip();
						// 保证缓冲区的数据全部写入
						   while (buffer.hasRemaining())
				            {
							   writableByteChannel.write(buffer);
				            }
						buffer.clear();
            	}
            log.info(outDir+"下载完成");
            os.flush();
            fileChannel.close();
            writableByteChannel.close();
        } catch (IOException e) {
           e.printStackTrace();
        }
        //文件的关闭放在finally中
        finally {
            try {
            	 if (fis != null) {
            		 fis.close();
                 }
            	 if (os != null) {
             		os.flush();
             		os.close();
             	}
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

}



public static void printInfo(long beginTime) {
	long endTime = System.currentTimeMillis();
	long total = endTime - beginTime;
	log.info("压缩耗时:" + total / 1000 + "秒");

}
}
 

2:简单测试

    @GetMapping(value = "/zip")
    @AnonymityAnnotation(access = true)
    public WebResponse<String> zip(@RequestParam("file") MultipartFile file) throws IOException {
        InputStream stream = file.getInputStream();
        System.out.println(stream);
        //下载压缩后的地址
        String path = "D:/91-69ddf076d28040d29e59aec22b65b150";
        //获取文件原本的名称
        String fileName = file.getOriginalFilename();
        System.out.println(fileName);
        String[] src = { path + "/" + fileName };
        String outDir = path + "/69.zip";
        try {
            ZipUtils.toZip(src, outDir, true);
        } catch (Exception e) {
        }
        return new WebResponse<String>().success("OK");
    }

3:效果图

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1181300.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

文件过大放不到U盘怎么办?三个方法轻松搞定!

文件过大放不了U盘我们可以从文件过大这个角度来解决一下这个问题&#xff0c;可以借助一些工具把文件压缩后&#xff0c;体积变小后&#xff0c;再放入U盘&#xff0c;使得u盘得到高效的利用&#xff0c;下面是推荐的一些好用的软件。 一、嗨格式压缩大师 是一款可以压缩多种…

idea 模板注释 {@link}

1. 新增组 2. 设置方法注释及变量 增加模板文本 ** * $param$ * return {link $return$} */3. 设置变量表达式 勾选跳过param 参数表达式 groovyScript("def result ;def params \"${_1}\".replaceAll([\\\\[|\\\\]|\\\\s], ).split(,).toList();def param…

【案例卡】clickhouse:多行数据拼接在一行

一、需求 针对clickhouse数据库中&#xff0c;group by 分组后的字符串字段&#xff0c;拼接处理在一行的问题实现。在mysql中&#xff0c;可以用group_concat()函数来实现&#xff0c;而clickhouse数据库不支持此函数&#xff0c;特此记录实现方式。 二、clickhouse相关函数…

C++模板元模板实战书籍讲解第一章题目讲解

目录 第一题 C代码示例 第二题 C代码示例 第三题 3.1 使用std::integral_constant模板类 3.2 使用std::conditional结合std::is_same判断 总结 第四题 C代码示例 第五题 C代码示例 第六题 C代码示例 第七题 C代码示例 总结 第一题 对于元函数来说&#xff0c;…

AIGPT重大升级,界面重新设计,功能更加饱满,用户体验升级

AIGPT AIGPT是一款功能强大的人工智能技术处理软件&#xff0c;不但拥有其他模型处理文本认知的能力还有AI绘画模型、拥有自身的插件库。 我们都知道使用ChatGPT是需要账号以及使用魔法的&#xff0c;实现其中的某一项对我们一般的初学者来说都是一次巨大的挑战&#xff0c;但…

录屏软件区域录制图片特效显示,电脑怎么区域局域放大录制屏幕

对应的视频链接 录屏软件区域录制图片特效显示&#xff0c;电脑怎么区域局域放大录制屏幕-CSDN直播录屏软件区域录制图片特效显示&#xff0c;电脑怎么区域局域放大录制屏幕图片特效显示软件可以定制https://live.csdn.net/v/341731 录屏软件区域录制图片特效显示&#xff0c…

socks5代理和https代理有什么不同?各自有哪些优点?

socks5代理和https代理是两种不同的代理服务&#xff0c;它们在实现方式、安全性和协议特点等方面存在差异。下面我们来详细了解一下这两种代理的优点。 一、socks5代理的优点 1. 速度快 socks5代理采用了TCP协议&#xff0c;能够有效地减少网络延迟和数据传输速度慢的问题&…

通过docker快速部署RabbitMq

查询镜像&#xff1a; docker search rabbitmq拉去RabbitMq镜像&#xff1a; docker pull rabbitmq:management创建数据卷&#xff1a; docker volume create rabbitmq-home运行容器&#xff1a; docker run -id --namerabbitmq -v rabbitmq-home:/var/lib/rabbitmq -p 156…

Steam余额红锁的原因,及红锁后申诉方法

CSGO饰品自动上架助手使用教程 安全的余额一般是通过充值卡充值获得&#xff0c;再加上交易手续费再转卖给你。一般便宜不到哪去。 但你别以为余额是安全的&#xff0c;就万事大吉了。照样有被红锁的可能性&#xff0c;比如这三种&#xff1a; 1、Steam市场巡查机制&#xff…

UML与PlantUML简介

UML与PlantUML 1、UML与PlantUML概述2、PlantUML使用 1、UML与PlantUML概述 UML&#xff08;Unified Modeling Language&#xff09;是一种统一建模语言&#xff0c;为面向对象开发系统的产品进行说明、可视化、和编制文档的一种标准语言&#xff0c;独立于任何具体程序设计语言…

番外---10.1 gcc+make调试程序

######### step0&#xff1a;理解程序调试&#xff1b; &#xff08;原始程序文件--->目标文件---->可执行文件&#xff1b;&#xff09; step1&#xff1a;掌握使用gcc的调试方法&#xff1b; step2&#xff1a;掌握使用make编译方法&#xff1b; ######### step0&…

JWT原理分析——JWT

了解为什么会有JWT的出现&#xff1f; 首先不得不提到一个知识叫做跨域身份验证&#xff0c;JWT的出现就是为了更好的解决这个问题&#xff0c;但是在没有JWT的时候&#xff0c;我们一般怎么做呢&#xff1f;一般使用Cookie和Session&#xff0c;流程大体如下所示&#xff1a;…

DVWA - 1

文章目录 Brute Forcelowhigh Command Injectionlowmediumhigh CSRFlowmediumhigh Brute Force low 1.进入到Brute Force页面&#xff0c;随机输入一个用户名及密码&#xff0c;点击登录。使用 BurpSuite查看拦截历史&#xff0c;找到该登录请求&#xff0c;右键send to intr…

第二章:人工智能深度学习教程-深度学习简介

深度学习是基于人工神经网络的机器学习的一个分支。它能够学习数据中的复杂模式和关系。在深度学习中&#xff0c;我们不需要显式地对所有内容进行编程。近年来&#xff0c;由于处理能力的进步和大型数据集的可用性&#xff0c;它变得越来越流行。因为它基于人工神经网络&#…

pytorch_神经网络构建5

文章目录 生成对抗网络自动编码器变分自动编码器重参数GANS自动编码器变分自动编码器gans网络Least Squares GANDeep Convolutional GANs 生成对抗网络 这起源于一种思想,假如有一个生成器,从原始图片那里学习东西,一个判别器来判别图片是真实的还是生成的, 假如生成的东西能以…

竞赛选题 深度学习手势识别算法实现 - opencv python

文章目录 1 前言2 项目背景3 任务描述4 环境搭配5 项目实现5.1 准备数据5.2 构建网络5.3 开始训练5.4 模型评估 6 识别效果7 最后 1 前言 &#x1f525; 优质竞赛项目系列&#xff0c;今天要分享的是 &#x1f6a9; 深度学习手势识别算法实现 - opencv python 该项目较为新颖…

【Spring】bean的自动装配

目录 一.byName 二.byType 快捷书写 people1 package org.example;public class People1 {public void eat(){System.out.println("吃饭");} }people2 package org.example;public class People2 {public void sleep(){System.out.println("睡觉");} …

校园安防监控系统升级改造方案:如何实现设备利旧上云与AI视频识别感知?

一、背景与需求分析 随着现代安防监控科技的兴起和在各行各业的广泛应用&#xff0c;监控摄像头成为众所周知的产品&#xff0c;也为人类的工作生活提供了很大的便利。由于科技的发达&#xff0c;监控摄像头的升级换代也日益频繁。每年都有不计其数的摄像头被拆掉闲置&#xf…

第十八章:Swing自述

18.1 Swing概述 18.2&#xff1a;Swing常用窗体 18.2.1&#xff1a;JFrame窗体 package eightth;import java.awt.*; //导入AWT包 import javax.swing.*; //导入Swing包public class JFreamTest {public static void main(String args[]) { // 主方法JFrame jf new JFrame()…

问题 N: A strange lift(BFS)

代码如下&#xff1a; #include<queue> #include<iostream> using namespace std; int main() {int num1;while (scanf("%d", &num) && num){queue<int> disp;int fir 0, end 0;int arr[209] { 0 };int visit[209] { 0 };int fl…