Java压缩Zip格式提速
小白程序员为了这事折腾了一天,试过换压缩格式,换压缩方式,使用多线程去压缩,都没有解决这个问题,最后公司的大佬帮忙解决了一下 给了下面一个使用多线程进行文件压缩的解决方案,具体逻辑暂时还没有理解,先搬运过来,以便于参考理解
/*** 压缩文件夹** @param zipOutName zip输出路径* @param paths 将要压缩的路径* @throws IOException* @throws ExecutionException* @throws InterruptedException*/public static void compressFiles(String zipOutName, String... paths) throws IOException, ExecutionException, InterruptedException {long start = System.currentTimeMillis();// 创建一个线程池对象ExecutorService executor = new ThreadPoolExecutor(10, 20, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(20), Executors.defaultThreadFactory(), new ThreadPoolExecutor.CallerRunsPolicy());// 压缩等级默认为速度优先compressFiles(zipOutName, executor, Deflater.BEST_SPEED, paths);long end = System.currentTimeMillis();log.info("压缩完成,耗时:" + (end - start) + " ms");}/*** 自定义线程池** @param zipOutName* @param executorService 线程池实现对象* @param paths* @throws IOException* @throws ExecutionException* @throws InterruptedException*/public static void compressFiles(String zipOutName, ExecutorService executorService, int level, String... paths) throws IOException, ExecutionException, InterruptedException {// 创建用于多线程压缩文件的对象ParallelScatterZipCreator parallelScatterZipCreator = new ParallelScatterZipCreator(executorService);// 输出文件流OutputStream outputStream = new FileOutputStream(zipOutName);// 输出Zip文件流ZipArchiveOutputStream zipArchiveOutputStream = new ZipArchiveOutputStream(outputStream);// 设置压缩等级zipArchiveOutputStream.setLevel(level);// 设置压缩的字符编码zipArchiveOutputStream.setEncoding("UTF-8");// 循环压缩各个路径的文件for (String path : paths) {File temp = new File(path);compress(parallelScatterZipCreator, temp, temp.getName());}// 将数据写入zip输出流parallelScatterZipCreator.writeTo(zipArchiveOutputStream);// 相关流的关闭zipArchiveOutputStream.close();outputStream.close();}/*** 遍历压缩** @param parallelScatterZipCreator 线程池压缩对象* @param inputFile 将要压缩的文件路径,绝对路径* @param relativePath 相对与压缩包内的路径* @throws IOException* @throws ExecutionException* @throws InterruptedException*/protected static void compress(ParallelScatterZipCreator parallelScatterZipCreator, File inputFile, String relativePath) throws IOException, ExecutionException, InterruptedException {// 文件流为空,返回if (inputFile == null) {return;}// 文件为文件夹,递归遍历文件if (inputFile.isDirectory()) {// 获取文件内的所有文件File[] files = inputFile.listFiles();if (files == null) {return;}// 遍历处理文件for (File file : files) {if (file.isDirectory()) {compress(parallelScatterZipCreator, new File(inputFile.getAbsolutePath() + "/" + file.getName()), relativePath + "/" + file.getName());} else {// 转化为InputStreamSupplier对象final InputStreamSupplier inputStreamSupplier = () -> {try {return new FileInputStream(file);} catch (FileNotFoundException e) {e.printStackTrace();return new NullInputStream(0);}};// 添加ZipArchiveEntity对象,这里的构造函数的值,name属性,是相对于zip文件内的路径ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(relativePath + "/" + file.getName());// 设置压缩算法zipArchiveEntry.setMethod(ZipArchiveEntry.DEFLATED);// 设置未压缩文件的大小zipArchiveEntry.setSize(file.length());// 添加添加ZipArchiveEntity对象到多线程压缩中parallelScatterZipCreator.addArchiveEntry(zipArchiveEntry, inputStreamSupplier);}}} else {// 当是文件时,直接处理final InputStreamSupplier inputStreamSupplier = () -> {try {return new FileInputStream(inputFile);} catch (FileNotFoundException e) {e.printStackTrace();return new NullInputStream(0);}};ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(inputFile.getName());zipArchiveEntry.setMethod(ZipArchiveEntry.DEFLATED);zipArchiveEntry.setSize(inputFile.length());parallelScatterZipCreator.addArchiveEntry(zipArchiveEntry, inputStreamSupplier);}}
最后再附上自己之前的代码片段,也尝试过创建线程进行多个List<File>文件压缩,结果到最后变成了多个线程向同一个文件内写自己的东西,最后还是没有成功
/*** 把文件集合打成zip压缩包** @param srcFiles 压缩文件集合* @param zipFile zip文件名* @throws RuntimeException 异常*/public void toZip(List<File> srcFiles, File zipFile) throws RuntimeException {long start = System.currentTimeMillis();if (zipFile == null) {log.error("压缩包文件名为空!");return;}if (!zipFile.getName().endsWith(".zip")) {log.error("压缩包文件名异常,zipFile={}", zipFile.getPath());return;}ZipOutputStream zos = null;FileOutputStream out = null;try {out = new FileOutputStream(zipFile);zos = new ZipOutputStream(out);for (File srcFile : srcFiles) {byte[] buf = new byte[BUFFER_SIZE];zos.putNextEntry(new ZipEntry(srcFile.getName()));int len;FileInputStream in = new FileInputStream(srcFile);while ((len = in.read(buf)) != -1) {zos.write(buf, 0, len);}in.close();}zos.closeEntry();long end = System.currentTimeMillis();log.info("压缩完成,耗时:" + (end - start) + " ms");} catch (Exception e) {log.error("ZipUtil toZip exception, ", e);throw new RuntimeException("zipFile error from ZipUtils", e);} finally {if (zos != null) {try {zos.close();out.close();} catch (Exception e) {log.error("ZipUtil toZip close exception, ", e);}}}}
文章参考:Java多线程Zip压缩_Youlingdada的博客-CSDN博客_java多线程zip
感谢大佬分享代码
Java压缩Zip格式提速相关推荐
- java压缩zip格式文件下载
1.页面js发送后台请求 window.location.href = basePath+"printWord/zipDownload?ids="+ ids + "&am ...
- 【Java导出zip格式压缩包】
最近写了一个Java导出zip格式的工具类,亲测有效,前提是需要导出的文件已经存在数据库,或者存到了服务器上,得让工具类能找到得到.本次导出支持doc,docx,pdf,xls,xlsx,ppt,tx ...
- java解析zip格式压缩包
java解析zip格式压缩包 做项目时遇到需要将zip格式的压缩包解析里面的图片 将里面的图片保存到文件夹 并且保存到数据库中关联起来 在上传时判断是否为zip格式的文件 @RequestMappin ...
- Java用ZIP格式压缩和解压缩文件
转载:java jdk实例宝典 感觉讲的很好就转载在这保存! java.util.zip包实现了Zip格式相关的类库,使用格式zip格式压缩和解压缩文件的时候,需要导入该包. 使用zipoutputs ...
- java 生成 zip格式 压缩文件
ackage org.fh.util;import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStr ...
- 如何压缩zip格式的文件
Java是孤立的"图书馆java.util.zip"在原有数据压缩的ZIP格式.整个概念是与straightforward相抵. 1.用"文件输入流"读取文件 ...
- java压缩zip文件中文乱码问题
--转自:http://riching.iteye.com/blog/579634 用java来打包文件生成压缩文件,有两个地方会出现乱码 1.内容的中文乱码问题,这个问题网上很多人给出了解决方法,两 ...
- java压缩zip文件夹错误_Java将文件或者文件夹压缩成zip(修复文件夹中存在多个文件报Stream Closed错误问题)...
项目场景: Java将文件或者文件夹压缩成zip(修复文件夹中存在多个文件报Stream Closed错误问题) 问题描述: 最近的项目需要将多级文件夹压缩成zip,网上找了几个工具类,都会报错,所以 ...
- centos解压与压缩zip格式文件
为方面日后使用,记录下压缩与解压zip文件 首先安装支持ZIP的工具 yum install -y unzip zip 解压zip文件 # 进入到对应文件目录下执行如下命令 unzip 文件名.zip ...
最新文章
- 智能算法中终止条件: “最大评估次数” or “最大迭代次数”
- 写在我第一个虚幻程序之前
- #define 的换行问题
- 【翻译】Pro LINQ Language Integrated Query in C# 2008 -- 第三章 (LINQ TO Objects) 第一节
- 对比es1.x和es2.0纹理加载方法
- java类体_计算机二级考试Java类之类声明以及类体
- 转:linux中fork()函数详解
- python 单链表节点怎么快速定义_线性表链式存储结构之单链表
- 阿里云服务器报 Liunx异常文件下载处理办法
- 蓝鸽英语学习平台_蓝鸽集团携手英特尔,共筑智慧校园新生态——蓝鸽amp;英特尔智慧校园建设高峰论坛顺利举办...
- 网站服务器修改内容,网站被收录后内容还可以修改吗?
- 自己用过最好用的pdf转word软件
- 苹果屏幕镜像_苹果屏幕镜像一直在转,秒懂投屏帮你解决
- opencv RGB 颜色 灰色图片显示
- 数组和链表 Array and Linked-List
- 第十二周项目四:银行系统(一)
- linux中exec的用法
- 小白必看:IT转行需要注意什么,这几个问题很重要
- CC2630 7x7 更改为5X5
- 一个普通视觉工程师对自己的要求:
热门文章
- 双十一闭眼入数码好物清单,值得入手的数码好物推荐
- FilterDispatcher-II
- Ubuntu16.04安装 双显卡安装Nvidia驱动 登录循环 黑屏(通用 终结此类问题)转载
- matlab转换为部分分式,【MATLAB用部分分式展开法资讯】MATLAB用部分分式展开法足球知识与常识 - 足球百科 - 599比分...
- 二阶段提交,三阶段提交,Paxos
- 2020最全java面试题
- s3c2410 NandFlash K9F1208U0A/ K9F1208U0B的读取操作
- mysql数据表名设置大小写不敏感(Linux Centos)
- 华为稳定版鸿蒙os花粉,华为鸿蒙OS系统被爆出BUG!花粉们却纷纷体验叫好:成鸿蒙系统特权?...
- js原生DOM属性值查找 getAttribute,设置setAttribute,移除removeAttribute