Java GZip 基于内存实现压缩和解压的方法
作者:超哥说码 发布时间:2023-05-24 12:47:29
GZip是常用的无损压缩算法实现,在Linux中较为常见,像我们在Linux安装软件时,基本都是.tar.gz格式。.tar.gz格式文件需要先对目录内文件进行tar压缩,然后使用GZip进行压缩。
本文针对基于磁盘的压缩和解压进行演示,演示只针对一层目录结构进行,多层目录只需递归操作进行即可。
Maven依赖
org.apache.commons: commons-compress: 1.19: 此依赖封装了很多压缩算法相关的工具类,提供的API还是相对比较底层,我们今天在它的基础上做进一步封装。
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.19</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
工具类
在实际应用中,对应不同需求,可能需要生成若干文件,然后将其压缩。在某些应用中,文件较小、文件数量较少且较为固定,频繁与磁盘操作,会带来不必要的效率影响。
工具类针对.tar.gz格式提供了compressByTar、decompressByTar、compressByGZip、decompressByGZip四个方法,用于处理.tar.gz格式压缩文件,代码如下:
package com.arhorchin.securitit.compress.gzip;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveInputStream;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.apache.commons.io.IOUtils;
/**
* @author Securitit.
* @note 基于内存以ZIP算法进行压缩和解压工具类.
*/
public class GZipRamUtil {
/**
* 使用TAR算法进行压缩.
* @param sourceFileBytesMap 待压缩文件的Map集合.
* @return 压缩后的TAR文件字节数组.
* @throws Exception 压缩过程中可能发生的异常,若发生异常,则返回的字节数组长度为0.
*/
public static byte[] compressByTar(Map<String, byte[]> tarFileBytesMap) throws Exception {
// 变量定义.
ByteArrayOutputStream tarBaos = null;
TarArchiveOutputStream tarTaos = null;
TarArchiveEntry tarTae = null;
try {
// 压缩变量初始化.
tarBaos = new ByteArrayOutputStream();
tarTaos = new TarArchiveOutputStream(tarBaos);
// // 将文件添加到TAR条目中.
for (Map.Entry<String, byte[]> fileEntry : tarFileBytesMap.entrySet()) {
tarTae = new TarArchiveEntry(fileEntry.getKey());
tarTae.setName(fileEntry.getKey());
tarTae.setSize(fileEntry.getValue().length);
tarTaos.putArchiveEntry(tarTae);
tarTaos.write(fileEntry.getValue());
tarTaos.closeArchiveEntry();
}
} finally {
if (tarTaos != null) {
tarTaos.close();
}
if (null == tarBaos) {
tarBaos = new ByteArrayOutputStream();
}
}
return tarBaos.toByteArray();
}
/**
* 使用TAR算法进行解压.
* @param sourceZipFileBytes TAR文件字节数组.
* @return 解压后的文件Map集合.
* @throws Exception 解压过程中可能发生的异常,若发生异常,返回Map集合长度为0.
*/
public static Map<String, byte[]> decompressByTar(byte[] sourceTarFileBytes) throws Exception {
// 变量定义.
TarArchiveEntry sourceTarTae = null;
ByteArrayInputStream sourceTarBais = null;
TarArchiveInputStream sourceTarTais = null;
Map<String, byte[]> targetFilesFolderMap = null;
try {
// 解压变量初始化.
targetFilesFolderMap = new HashMap<String, byte[]>();
sourceTarBais = new ByteArrayInputStream(sourceTarFileBytes);
sourceTarTais = new TarArchiveInputStream(sourceTarBais);
// 条目解压缩至Map中.
while ((sourceTarTae = sourceTarTais.getNextTarEntry()) != null) {
targetFilesFolderMap.put(sourceTarTae.getName(), IOUtils.toByteArray(sourceTarTais));
}
} finally {
if (sourceTarTais != null)
sourceTarTais.close();
}
return targetFilesFolderMap;
}
/**
* 使用GZIP算法进行压缩.
* @param sourceFileBytesMap 待压缩文件的Map集合.
* @return 压缩后的GZIP文件字节数组.
* @throws Exception 压缩过程中可能发生的异常,若发生异常,则返回的字节数组长度为0.
*/
public static byte[] compressByGZip(byte[] sourceFileBytes) throws IOException {
// 变量定义.
ByteArrayOutputStream gzipBaos = null;
GzipCompressorOutputStream gzipGcos = null;
try {
// 压缩变量初始化.
gzipBaos = new ByteArrayOutputStream();
gzipGcos = new GzipCompressorOutputStream(gzipBaos);
// 采用commons-compress提供的方式进行压缩.
gzipGcos.write(sourceFileBytes);
} finally {
if (gzipGcos != null) {
gzipGcos.close();
}
if (null == gzipBaos) {
gzipBaos = new ByteArrayOutputStream();
}
}
return gzipBaos.toByteArray();
}
/**
* 使用GZIP算法进行解压.
* @param sourceGZipFileBytes GZIP文件字节数组.
* @return 解压后的文件Map集合.
* @throws Exception 解压过程中可能发生的异常,若发生异常,则返回的字节数组长度为0.
*/
public static byte[] decompressByGZip(byte[] sourceGZipFileBytes) throws IOException {
// 变量定义.
ByteArrayOutputStream gzipBaos = null;
ByteArrayInputStream sourceGZipBais = null;
GzipCompressorInputStream sourceGZipGcis = null;
try {
// 解压变量初始化.
gzipBaos = new ByteArrayOutputStream();
sourceGZipBais = new ByteArrayInputStream(sourceGZipFileBytes);
sourceGZipGcis = new GzipCompressorInputStream(sourceGZipBais);
// 采用commons-compress提供的方式进行解压.
gzipBaos.write(IOUtils.toByteArray(sourceGZipGcis));
} finally {
if (sourceGZipGcis != null)
sourceGZipGcis.close();
}
return gzipBaos.toByteArray();
}
}
工具类测试
在Maven依赖引入正确的情况下,复制上面的代码到项目中,修改package,可以直接使用,下面我们对工具类进行简单测试。测试类代码如下:
package com.arhorchin.securitit.compress.gzip;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.io.FileUtils;
import com.arhorchin.securitit.compress.gzip.GZipRamUtil;
/**
* @author Securitit.
* @note GZipRamUtil工具类测试.
*/
public class GZipRamUtilTester {
public static void main(String[] args) throws Exception {
Map<String, byte[]> fileBytesMap = null;
fileBytesMap = new HashMap<String, byte[]>();
// 设置文件列表.
File dirFile = new File("C:/Users/Administrator/Downloads/个人文件/2020-07-13/files");
for (File file : dirFile.listFiles()) {
fileBytesMap.put(file.getName(), FileUtils.readFileToByteArray(file));
}
byte[] ramBytes = GZipRamUtil.compressByTar(fileBytesMap);
ramBytes = GZipRamUtil.compressByGZip(ramBytes);
FileUtils.writeByteArrayToFile(new File("C:/Users/Administrator/Downloads/个人文件/2020-07-13/ram.tar.gz"), ramBytes);
ramBytes = GZipRamUtil.decompressByGZip(ramBytes);
fileBytesMap = GZipRamUtil.decompressByTar(ramBytes);
System.out.println(fileBytesMap.size());
}
}
运行测试后,通过查看ram.tar.gz和控制台输出解压后文件数量,可以确认工具类运行结果无误。
总结
1) 在小文件、文件数量较小且较为固定时,提倡使用内存压缩和解压方式。使用内存换时间,减少频繁的磁盘操作。
2) 在大文件、文件数量较大时,提倡使用磁盘压缩和解压方式。过大文件对服务会造成过度的负载,磁盘压缩和解压可以缓解这种压力。《Java GZip 基于磁盘实现压缩和解压》
来源:https://blog.csdn.net/securitit/article/details/108156074


猜你喜欢
- 对Element和Node有困惑是因为对xml整个结构不了解,以下作为一个简要概述:以下图为w3c.org网站的xml文档树图:从上图可以看
- 序列化序列化:将对象转换为二进制序列在网络中传输或保存到磁盘反序列化:从网络或磁盘中将二进制序列转换为对象注意:对象必须实现Serializ
- 一、概述热修复这项技术,基本上已经成为项目比较重要的模块了。主要因为项目在上线之后,都难免会有各种问题,而依靠发版去修复问题,成本太高了。现
- 本人亲测,在使用IDEA使用Maven模板创建项目或者在当前项目中New Project,Maven的以下三个配置参数会重置使用C:\Use
- 网上看到的很多winform窗体圆角设计代码都比较累赘,这里分享一个少量代码就可以实现的圆角。主要运用了System.Drawing.Dra
- 本文实例为大家分享了Android设置默认锁屏壁纸接口的具体代码,供大家参考,具体内容如下完成自定义service后,接下来就是具体实现接口
- 一、单链表(Linked List)简介二、单链表的各种操作1.单链表的创建和遍历2.单链表的按顺序插入节点 以及节点的修改3.单链表节点的
- 页眉位于文档中每个页面的顶部区域,常用于显示文档的附加信息,可以插入时间、图形、公司微标、文档标题、文件名或作者姓名等;页脚位于文档中每个页
- 前言volatile相关的知识其实自己一直都是有掌握的,能大概讲出一些知识,例如:它可以保证可见性;禁止指令重排。这两个特性张口就来,但要再
- 对网页中各种不同格式的发布时间进行抽取,将发布时间以规整的“yyyy-MM-dd HH:mm:ss”格式表示出来,只能尽量追求精确,但是因为
- 手动编写 SQL 语句和映射实体类的过程常常是繁琐且易出错的。这时,我们就可以借助 MyBatis Generator (MBG) 这个强大
- 1. 基本数据类型(以int为例,其他类似):Controller代码:@RequestMapping("saysth.do&qu
- 很多小伙伴刚刚接触.net这一平台,可能不清楚如何安装最新版本VS 来搭建一个好用的编译器;本文将引导大家安装VS2019 C#语言的安装第
- 在前面仿华为加载动画、仿网易音乐听歌识曲-麦克风动画中,我们通过绘图的基础知识完成了简单的绘制。在本例中,我们将绘制常见的验证码。一、效果图
- this可能是几乎所有有一点面向对象思想的语言都会引用到的变量,java自然不例外。只是,this有多少种用法,我也不知道了,让我们来see
- 前言Spring内置的工具类里,最喜欢用的就是文件读写这一部分,虽然原生的写法也没几句,但是就是懒,不想循环、判断什么的,直接调用现成的静态
- 控制器Controller控制器复杂提供访问应用程序的行为,通常通过接口定义或注解定义两种方法实现。控制器负责解析用户的请求并将其转换为一个
- 本实例为大家分享了Android实现短信验证码自动填写功能,供大家参考,具体内容如下实现思路很简单:1、在需要输入验证码的Activity代
- Android webview 从Lollipop(5.0)开始webview默认不允许混合模式,https当中不能加载http资源,需要设
- SpringBoot后台如何实现文件上传下载?最近做的一个项目涉及到文件上传与下载。前端上传采用百度webUploader插件。有关该插件的