读网文《将20M文件从30秒压缩到1秒,我是如何做到的?》做实验
先在微信公众号上看到网文《将20M文件从30秒压缩到1秒,我是如何做到的?》,然后在网上搜索了一下,看到了原文:https://www.jianshu.com/p/2e46ccb125ef
很惊奇他把时间压缩到了三十分之一,于是就有了做实验验证的想法。
我的实验对象是apache-tomcat-9.0.30.zip,Redis-x64-3.2.100.msi,Redis-x64-3.2.100.zip这三个文件,加起来21M,比作者的十张2M图片略多。
任务是把它们三个压缩成一个result.zip文件。
首先我实验的是rugularZip方法,也是作者提到的第一种方法:
// time elapsed:1s652ms
private boolean rugularZip(String[] fromFiles,String toFile) {
File zipFile=new File(toFile);
byte[] buffer=new byte[BUFFER_SIZE];
int readLen=0; try {
ZipOutputStream zipOut=new ZipOutputStream(new FileOutputStream(zipFile)) ; for(String file:fromFiles) {
File fileWillZip=new File(file); if(fileWillZip.exists()) {
InputStream inputStream=new BufferedInputStream(new FileInputStream(fileWillZip));
String entryName=fileWillZip.getName();// entryName should be a valid filename,no path seperater allowed
zipOut.putNextEntry(new ZipEntry(entryName)); while((readLen=inputStream.read(buffer,0,BUFFER_SIZE))!=-1) {
zipOut.write(buffer,0,readLen);
}
inputStream.close(); }
} zipOut.close();
}catch(Exception e) {
e.printStackTrace();
return false;
} return true;
}
用时1秒652毫秒。
接下来实验的是bufferOuputZip方法,也就是作者提到的第二种方法:
// time elapsed:1s207ms
private boolean bufferOuputZip(String[] fromFiles,String toFile) {
File zipFile=new File(toFile);
byte[] buffer=new byte[BUFFER_SIZE];
int readLen=0; try {
ZipOutputStream zipOut=new ZipOutputStream(new FileOutputStream(zipFile)) ;
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(zipOut) ; for(String file:fromFiles) {
File fileWillZip=new File(file); if(fileWillZip.exists()) {
InputStream inputStream=new BufferedInputStream(new FileInputStream(fileWillZip));
String entryName=fileWillZip.getName();// entryName should be a valid filename,no path seperater allowed
zipOut.putNextEntry(new ZipEntry(entryName)); while((readLen=inputStream.read(buffer,0,BUFFER_SIZE))!=-1) {
bufferedOutputStream.write(buffer,0,readLen);
}
inputStream.close();
}
} bufferedOutputStream.flush();
zipOut.close(); return true;
}catch(Exception e) {
e.printStackTrace();
return false;
}
}
用时1秒207毫秒,少了四分之一。
接下来实验作者提出的第三种方法:
// elapsed:1s188ms
private boolean nioChannalZip(String[] fromFiles,String toFile) {
File zipFile=new File(toFile); try {
ZipOutputStream zipOut=new ZipOutputStream(new FileOutputStream(zipFile)) ;
WritableByteChannel wChannel=Channels.newChannel(zipOut); for(String file:fromFiles) {
File fileWillZip=new File(file); if(fileWillZip.exists()) {
FileChannel readChannel=new FileInputStream(fileWillZip).getChannel(); String entryName=fileWillZip.getName();// entryName should be a valid filename,no path seperater allowed
zipOut.putNextEntry(new ZipEntry(entryName)); readChannel.transferTo(0, readChannel.size(),wChannel) ;
readChannel.close();
}
} wChannel.close();
zipOut.close(); return true;
}catch(Exception e) {
e.printStackTrace();
return false;
}
}
一秒188毫秒,没少多少。
接下来再看作者又提到了内存映射文件,他又说和第三种方法速度差不多哦,算了我就不试了。
作者最后又提到pip,我一看原来是用线程,这当然快了,因为主线程只要调用压缩线程就可以返回了,压缩线程消耗的时间不计算在主线程运行时间内,运行当然是秒回。
当然pip里面有个阻塞回调的过程,这消耗了一些时间。
更新DB,写文件都可以另起线程运行,这也是以空间换时间的方法之一。
完整程序:
package zip; import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; // Used to zip a file
public class FileZipper {
private static final int BUFFER_SIZE = 1024; public boolean compressFilesToZip(String[] files,String zipfile) {
return threadZip(files,zipfile);
} private boolean threadZip(String[] fromFiles,String toFile) {
new ZipThread(fromFiles,toFile).start();;
return true;
} // elapsed:1s188ms
private boolean nioChannalZip(String[] fromFiles,String toFile) {
File zipFile=new File(toFile); try {
ZipOutputStream zipOut=new ZipOutputStream(new FileOutputStream(zipFile)) ;
WritableByteChannel wChannel=Channels.newChannel(zipOut); for(String file:fromFiles) {
File fileWillZip=new File(file); if(fileWillZip.exists()) {
FileChannel readChannel=new FileInputStream(fileWillZip).getChannel(); String entryName=fileWillZip.getName();// entryName should be a valid filename,no path seperater allowed
zipOut.putNextEntry(new ZipEntry(entryName)); readChannel.transferTo(0, readChannel.size(),wChannel) ;
readChannel.close();
}
} wChannel.close();
zipOut.close(); return true;
}catch(Exception e) {
e.printStackTrace();
return false;
}
} // time elapsed:1s207ms
private boolean bufferOuputZip(String[] fromFiles,String toFile) {
File zipFile=new File(toFile);
byte[] buffer=new byte[BUFFER_SIZE];
int readLen=0; try {
ZipOutputStream zipOut=new ZipOutputStream(new FileOutputStream(zipFile)) ;
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(zipOut) ; for(String file:fromFiles) {
File fileWillZip=new File(file); if(fileWillZip.exists()) {
InputStream inputStream=new BufferedInputStream(new FileInputStream(fileWillZip));
String entryName=fileWillZip.getName();// entryName should be a valid filename,no path seperater allowed
zipOut.putNextEntry(new ZipEntry(entryName)); while((readLen=inputStream.read(buffer,0,BUFFER_SIZE))!=-1) {
bufferedOutputStream.write(buffer,0,readLen);
}
inputStream.close();
}
} bufferedOutputStream.flush();
zipOut.close(); return true;
}catch(Exception e) {
e.printStackTrace();
return false;
}
} // time elapsed:1s652ms
private boolean rugularZip(String[] fromFiles,String toFile) {
File zipFile=new File(toFile);
byte[] buffer=new byte[BUFFER_SIZE];
int readLen=0; try {
ZipOutputStream zipOut=new ZipOutputStream(new FileOutputStream(zipFile)) ; for(String file:fromFiles) {
File fileWillZip=new File(file); if(fileWillZip.exists()) {
InputStream inputStream=new BufferedInputStream(new FileInputStream(fileWillZip));
String entryName=fileWillZip.getName();// entryName should be a valid filename,no path seperater allowed
zipOut.putNextEntry(new ZipEntry(entryName)); while((readLen=inputStream.read(buffer,0,BUFFER_SIZE))!=-1) {
zipOut.write(buffer,0,readLen);
}
inputStream.close(); }
} zipOut.close();
}catch(Exception e) {
e.printStackTrace();
return false;
} return true;
} /**
* change seconds to DayHourMinuteSecond format
*
* @param startMs
* @param endMs
* @return
*/
private static String ms2DHMS(long startMs, long endMs) {
String retval = null;
long secondCount = (endMs - startMs) / 1000;
String ms = (endMs - startMs) % 1000 + "ms"; long days = secondCount / (60 * 60 * 24);
long hours = (secondCount % (60 * 60 * 24)) / (60 * 60);
long minutes = (secondCount % (60 * 60)) / 60;
long seconds = secondCount % 60; if (days > 0) {
retval = days + "d" + hours + "h" + minutes + "m" + seconds + "s";
} else if (hours > 0) {
retval = hours + "h" + minutes + "m" + seconds + "s";
} else if (minutes > 0) {
retval = minutes + "m" + seconds + "s";
} else if(seconds > 0) {
retval = seconds + "s";
}else {
return ms;
} return retval + ms;
} public static String calculateElaspedTime(long startMs) {
long endMs = System.currentTimeMillis();
return ms2DHMS(startMs,endMs);
} public static void main(String[] args) {
String[] files= {"D:\\usr\\apache-tomcat-9.0.30.zip",
"D:\\usr\\Redis-x64-3.2.100.msi",
"D:\\usr\\Redis-x64-3.2.100.zip"};
String zipfile="D:\\usr\\result.zip"; long startMs = System.currentTimeMillis();
FileZipper fz=new FileZipper();
boolean isCreated=fz.compressFilesToZip(files, zipfile);
if(isCreated) {
System.out.println("File:'"+zipfile+"' created,time elapsed:"+calculateElaspedTime(startMs));
}
}
}
package zip; import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.WritableByteChannel;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream; public class ZipThread extends Thread{
private String[] files;
private String zipfile; public ZipThread(String[] files,String zipfile) {
this.files=files;
this.zipfile=zipfile;
} public void run() {
nioChannalZip(this.files,this.zipfile);
} private boolean nioChannalZip(String[] fromFiles,String toFile) {
File zipFile=new File(toFile); try {
ZipOutputStream zipOut=new ZipOutputStream(new FileOutputStream(zipFile)) ;
WritableByteChannel wChannel=Channels.newChannel(zipOut); for(String file:fromFiles) {
File fileWillZip=new File(file); if(fileWillZip.exists()) {
FileChannel readChannel=new FileInputStream(fileWillZip).getChannel(); String entryName=fileWillZip.getName();// entryName should be a valid filename,no path seperater allowed
zipOut.putNextEntry(new ZipEntry(entryName)); readChannel.transferTo(0, readChannel.size(),wChannel) ;
readChannel.close();
}
} wChannel.close();
zipOut.close(); return true;
}catch(Exception e) {
e.printStackTrace();
return false;
}
}
}
--END-- 2020-01-06 14:54
读网文《将20M文件从30秒压缩到1秒,我是如何做到的?》做实验的更多相关文章
- 压缩20M文件从30秒到1秒的优化过程
文章来源公众号:IT牧场 有一个需求需要将前端传过来的10张照片,然后后端进行处理以后压缩成一个压缩包通过网络流传输出去.之前没有接触过用Java压缩文件的,所以就直接上网找了一个例子改了一下用了,改 ...
- Pandas 基础(4) - 读/写 Excel 和 CSV 文件
这一节将分别介绍读/写 Excel 和 CSV 文件的各种方式: - 读入 CSV 文件 首先是准备一个 csv 文件, 这里我用的是 stock_data.csv, 文件我已上传, 大家可以直接下载 ...
- Unity shader 官网文档全方位学习(一)
转载:https://my.oschina.net/u/138823/blog/181131 摘要: 这篇文章主要介绍Surface Shaders基础及Examples详尽解析 What?? Sha ...
- 【VR】Leap Motion 官网文档 FingerModel (手指模型)
前言: 感谢关注和支持这个Leap Motion系列翻译的朋友们,非常抱歉因为工作原因非常久没有更新,今后这个翻译还会继续(除非官方直接给出中文文档).本篇献给大家的是 <FingerModel ...
- Spring Security 官网文档学习
文章目录 通过`maven`向普通的`WEB`项目中引入`spring security` 配置 `spring security` `configure(HttpSecurity)` 方法 自定义U ...
- Atitit 基于图片图像 与文档混合文件夹的分类
Atitit 基于图片图像 与文档混合文件夹的分类 太小的文档(txt doc csv exl ppt pptx)单独分类 Mov10KminiDoc 但是可能会有一些书法图片迁移,因为他们很微小,需 ...
- php 读取文件头判断文件类型的实现代码
php代码实现读取文件头判断文件类型,支持图片.rar.exe等后缀. 例子: <?php $filename = "11.jpg"; //为图片的路径可以用d:/uploa ...
- php通过文件头检测文件类型通用类(zip,rar…)(转)
在做web应用时候,通过web扩展名判断上存文件类型,这个是我们常使用的.有时候我们这样做还不完善.可能有些人上存一些文件,但是他通过修改 扩展名,让在我们的文件类型之内. 单实际访问时候又不能展示( ...
- 部署openstack的官网文档解读mysql的配置文件
部署openstack的官网文档解读mysql的配置文件(使用与ubutu和centos7等系统) author:headsen chen 2017-10-12 16:57:11 个人原创,严禁转载 ...
随机推荐
- 4、Java基本数据类型
一.基本数据类型 1.基本数据类型 JAVA中一共有八种基本数据类型,他们分别是 byte.short.int.long.float.double.char.boolean 类型 型别 字节 取值范围 ...
- Docker 搭建 GitLab
Docker 搭建 GitLab 步骤 # 创建目录 mkdir -p /usr/local/gitlab && cd /usr/local/gitlab # 创建映射目录 mkdir ...
- 2020-06-15:Redis分布式锁怎么解锁?
福哥答案2020-06-15: 答案来自群成员:1.setnx:del2.set:lua+del3.redisson:@Overridepublic void unlock(String lockKe ...
- 2020-04-23:假设一个订单的编号规则是AAAAOrder2020-0000001,AAAAOrder2020-0000002....后面的数字是自增长,如果订单号码达到AAAAOrder2020-1000000(100万),数据库中应该有100万条数据,此时我随机删除2条数据(物理删除,且不考虑日志和备份),请问怎么找到删掉的数据的编号?给出解题思路即可,答案需要在1秒内运行得到。
福哥答案2020-04-23: 分批查询:分成500次count(),每次count()肯定小于等于2000条数据,经过测试,一次count()在.1ms左右,500次就是500ms.二分法(时间微超 ...
- C#LeetCode刷题之#263-丑数(Ugly Number)
问题 该文章的最新版本已迁移至个人博客[比特飞],单击链接 https://www.byteflying.com/archives/3862 访问. 编写一个程序判断给定的数是否为丑数.丑数就是只包含 ...
- GitHub 热点速览 Vol.32:VScode 韭菜基金插件,极大提高“工作”效率
作者:HelloGitHub-小鱼干 摘要:有什么比干着本职工作--编码,而又兼顾"外快"--炒股更有开心的事情呢?leek-fund 就是这么一个极大提升你工作幸福度和效率的插件 ...
- 【IDE】WebStorm 调整Tab缩进为2空格 -- 为遵循ESLint语法规范
步骤一 修改这三处的值为:2 步骤二 把这两处默认的勾选去掉,不让其detection当前文件的Tab缩进 注意! 通过上面两个步骤,我们只是改变了在JS文件的Tab缩进改为2个空格 但是,*.vue ...
- [PyTorch 学习笔记] 1.2 Tensor(张量)介绍
本章代码: https://github.com/zhangxiann/PyTorch_Practice/blob/master/lesson1/tensor_introduce1.py https: ...
- xss-labs 通关学习笔记
xss-labs 学习 By:Mirror王宇阳 time:2020/04/06 level1 我们进入到这个页面之后,快速关注到几个点,Xss注重的输入点,这里的输入点首先在URL栏中找到了name ...
- DataNode(面试开发重点)
1 DataNode工作机制 DataNode工作机制,如图所示. 1)一个数据块在DataNode上以文件形式存储在磁盘上,包括两个文件,一个是数据本身,一个是元数据包括数据块的长度,块数据的校验和 ...