GZip是常用的无损压缩算法实现,在Linux中较为常见,像我们在Linux安装软件时,基本都是.tar.gz格式。.tar.gz格式文件需要先对目录内文件进行tar压缩,然后使用GZip进行压缩。

本文针对基于磁盘的压缩和解压进行演示,演示只针对一层目录结构进行,多层目录只需递归操作进行即可。

Maven依赖

org.apache.commons: commons-compress: 1.19: 此依赖封装了很多压缩算法相关的工具类,提供的API还是相对比较底层,我们今天在它的基础上做进一步封装。

org.apache.commons

commons-compress

1.19

log4j

log4j

1.2.17

工具类

其实,在通常情况下,我们都是在磁盘上进行压缩和解压操作的,这样虽然增加了操作的复杂度,但是却无形中避免了一些问题。

工具类针对.tar.gz格式提供了compressByTar、decompressByTar、compressByGZip、decompressByGZip四个方法,用于处理.tar.gz格式压缩文件,代码如下:

package com.arhorchin.securitit.compress.gzip;

import java.io.BufferedInputStream;

import java.io.BufferedOutputStream;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileOutputStream;

import java.io.IOException;

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.compress.utils.IOUtils;

import org.apache.log4j.Logger;

/**

* @author Securitit.

* @note 基于磁盘以GZIP算法进行压缩和解压工具类.

*/

public class GZipDiskUtil {

/**

* logger.

*/

private static Logger logger = Logger.getLogger(GZipDiskUtil.class);

/**

* UTF-8字符集.

*/

public static String CHARSET_UTF8 = "UTF-8";

/**

* 使用TAR算法进行压缩.

* @param sourceFolderPath 待进行压缩的文件夹路径.

* @param targetTarFilePath 压缩后的TAR文件存储目录.

* @return 压缩是否成功.

* @throws Exception 压缩过程中可能发生的异常.

*/

public static boolean compressByTar(String sourceFolderPath, String targetTarFilePath) throws Exception {

// 变量定义.

File sourceFolderFile = null;

FileOutputStream targetTarFos = null;

TarArchiveOutputStream targetTartTaos = null;

TarArchiveEntry targetTarTae = null;

try {

// 压缩变量初始化.

sourceFolderFile = new File(sourceFolderPath);

targetTarFos = new FileOutputStream(new File(targetTarFilePath));

targetTartTaos = new TarArchiveOutputStream(targetTarFos);

// 将文件添加到ZIP条目中.

for (File file : sourceFolderFile.listFiles()) {

try (FileInputStream fis = new FileInputStream(file);

BufferedInputStream bis = new BufferedInputStream(fis);) {

targetTarTae = new TarArchiveEntry(file);

targetTarTae.setName(file.getName());

targetTartTaos.putArchiveEntry(targetTarTae);

targetTartTaos.write(IOUtils.toByteArray(bis));

targetTartTaos.closeArchiveEntry();

}

}

} catch (Exception ex) {

logger.info("GZipDiskUtil.compressByTar.", ex);

return false;

} finally {

if (targetTartTaos != null)

targetTartTaos.close();

if (targetTarFos != null)

targetTarFos.close();

}

return true;

}

/**

* 使用TAR算法进行解压.

* @param sourceTarPath 待解压文件路径.

* @param targetFolderPath 解压后文件夹目录.

* @return 解压是否成功.

* @throws Exception 解压过程中可能发生的异常.

*/

public static boolean decompressByTar(String sourceTarPath, String targetFolderPath) throws Exception {

// 变量定义.

FileInputStream sourceTarFis = null;

TarArchiveInputStream sourceTarTais = null;

TarArchiveEntry sourceTarTae = null;

File singleEntryFile = null;

try {

// 解压定义初始化.

sourceTarFis = new FileInputStream(new File(sourceTarPath));

sourceTarTais = new TarArchiveInputStream(sourceTarFis);

// 条目解压缩至指定文件夹目录下.

while ((sourceTarTae = sourceTarTais.getNextTarEntry()) != null) {

singleEntryFile = new File(targetFolderPath + File.separator + sourceTarTae.getName());

try (FileOutputStream fos = new FileOutputStream(singleEntryFile);

BufferedOutputStream bos = new BufferedOutputStream(fos);) {

bos.write(IOUtils.toByteArray(sourceTarTais));

}

}

} catch (Exception ex) {

logger.info("GZipDiskUtil.decompressByTar.", ex);

return false;

} finally {

if (sourceTarTais != null)

sourceTarTais.close();

if (sourceTarFis != null)

sourceTarFis.close();

}

return true;

}

/**

* 使用GZIP算法进行压缩.

* @param sourceFilePath 待进行压缩的文件路径.

* @param targetGZipFilePath 压缩后的GZIP文件存储目录.

* @return 压缩是否成功.

* @throws Exception 压缩过程中可能发生的异常.

*/

public static boolean compressByGZip(String sourceFilePath, String targetGZipFilePath) throws IOException {

// 变量定义.

FileInputStream sourceFileFis = null;

BufferedInputStream sourceFileBis = null;

FileOutputStream targetGZipFileFos = null;

BufferedOutputStream targetGZipFileBos = null;

GzipCompressorOutputStream targetGZipFileGcos = null;

try {

// 压缩变量初始化.

sourceFileFis = new FileInputStream(new File(sourceFilePath));

sourceFileBis = new BufferedInputStream(sourceFileFis);

targetGZipFileFos = new FileOutputStream(targetGZipFilePath);

targetGZipFileBos = new BufferedOutputStream(targetGZipFileFos);

targetGZipFileGcos = new GzipCompressorOutputStream(targetGZipFileBos);

// 采用commons-compress提供的方式进行压缩.

targetGZipFileGcos.write(IOUtils.toByteArray(sourceFileBis));

} catch (Exception ex) {

logger.info("GZipDiskUtil.compressByGZip.", ex);

return false;

} finally {

if (targetGZipFileGcos != null)

targetGZipFileGcos.close();

if (targetGZipFileBos != null)

targetGZipFileBos.close();

if (targetGZipFileFos != null)

targetGZipFileFos.close();

if (sourceFileBis != null)

sourceFileBis.close();

if (sourceFileFis != null)

sourceFileFis.close();

}

return true;

}

/**

* 使用GZIP算法进行解压.

* @param sourceGZipFilePath 待解压文件路径.

* @param targetFilePath 解压后文件路径.

* @return 解压是否成功.

* @throws @throws Exception 解压过程中可能发生的异常.

*/

public static boolean decompressByGZip(String sourceGZipFilePath, String targetFilePath) throws IOException {

// 变量定义.

FileInputStream sourceGZipFileFis = null;

BufferedInputStream sourceGZipFileBis = null;

FileOutputStream targetFileFos = null;

GzipCompressorInputStream sourceGZipFileGcis = null;

try {

// 解压变量初始化.

sourceGZipFileFis = new FileInputStream(new File(sourceGZipFilePath));

sourceGZipFileBis = new BufferedInputStream(sourceGZipFileFis);

sourceGZipFileGcis = new GzipCompressorInputStream(sourceGZipFileBis);

targetFileFos = new FileOutputStream(new File(targetFilePath));

// 采用commons-compress提供的方式进行解压.

targetFileFos.write(IOUtils.toByteArray(sourceGZipFileGcis));

} catch (Exception ex) {

logger.info("GZipDiskUtil.decompressByGZip.", ex);

return false;

} finally {

if (sourceGZipFileGcis != null)

sourceGZipFileGcis.close();

if (sourceGZipFileBis != null)

sourceGZipFileBis.close();

if (sourceGZipFileFis != null)

sourceGZipFileFis.close();

if (targetFileFos != null)

targetFileFos.close();

}

return true;

}

}

工具类测试

在Maven依赖引入正确的情况下,复制上面的代码到项目中,修改package,可以直接使用,下面我们对工具类进行简单测试。测试类代码如下:

package com.arhorchin.securitit.compress.gzip;

import com.arhorchin.securitit.compress.gzip.GZipDiskUtil;

/**

* @author Securitit.

* @note GZipDiskUtil工具类测试.

*/

public class GZipDiskUtilTester {

public static void main(String[] args) throws Exception {

GZipDiskUtil.compressByTar("C:/Users/Administrator/Downloads/个人文件/2020-07-13/files", "C:/Users/Administrator/Downloads/个人文件/2020-07-13/disk.tar");

GZipDiskUtil.compressByGZip("C:/Users/Administrator/Downloads/个人文件/2020-07-13/disk.tar", "C:/Users/Administrator/Downloads/个人文件/2020-07-13/disk.tar.gz");

GZipDiskUtil.decompressByGZip("C:/Users/Administrator/Downloads/个人文件/2020-07-13/disk.tar.gz", "C:/Users/Administrator/Downloads/个人文件/2020-07-13/disk-untar.tar");

GZipDiskUtil.decompressByTar("C:/Users/Administrator/Downloads/个人文件/2020-07-13/disk-untar.tar", "C:/Users/Administrator/Downloads/个人文件/2020-07-13/disk-untar");

}

}

运行测试后,通过查看disk.tar、disk.tar.gz、disk-untar.tar和解压的目录,可以确认工具类运行结果无误。

总结

1) 在小文件、文件数量较小且较为固定时,提倡使用内存压缩和解压方式。使用内存换时间,减少频繁的磁盘操作。《Java GZip 基于内存实现压缩和解压》

2) 在大文件、文件数量较大时,提倡使用磁盘压缩和解压方式。过大文件对服务会造成过度的负载,磁盘压缩和解压可以缓解这种压力。

原文链接:https://blog.csdn.net/securitit/article/details/108156025

java gzip 文件夹_Java GZip 基于磁盘实现压缩和解压的方法相关推荐

  1. java 解压到内存,Java GZip 基于内存实现压缩和解压的方法

    欢迎大家关注本博,同时欢迎大家评论交流,可以给个赞哦!!! GZip是常用的无损压缩算法实现,在Linux中较为常见,像我们在Linux安装软件时,基本都是.tar.gz格式..tar.gz格式文件需 ...

  2. java zip 文件夹_Java Zip文件文件夹示例

    java zip 文件夹 Today we will look into java zip file example. We will also compress a folder and creat ...

  3. linux bzip2压缩文件,bzip2命令_Linux bzip2命令:压缩和解压文件(.bz2文件)

    有时候你会发现并不是所有的 Linux 压缩包都是以 .tar.gz 为后缀的,有些压缩包的后缀是 .tar.bz2.这个 .tar.bz2 又是什么呢?它就是本文的主角:bzip2 压缩工具. 有了 ...

  4. mac 命令行 解压7z文件_如何在Mac上快速压缩和解压文件?Mac上解压和压缩文件的方法...

    苹果mac电脑怎么压缩和解压文件?Mac电脑仅默认支持把文件压缩成zip格式,解压成zip.tar.gz,bz2等格式,有些操作需要安装第三方软件来完成,这篇文章为大家带来几种关于在Mac上解压和压缩 ...

  5. linux带密码解压密码,linux 下文件加密压缩和解压的方法

    方法一:用tar命令 对文件加密压缩和解压 压缩: [html] view plain copy tar -zcf - filename |openssl des3 -salt -k password ...

  6. linux 下文件加密压缩和解压的方法

    方法一:用tar命令 对文件加密压缩和解压 压缩: tar -zcf - filename |openssl des3 -salt -k password | dd of=filename.des3 ...

  7. java 接口文件夹_Java NIO.2 使用Path接口来监听文件、文件夹变化

    Java7对NIO进行了大的改进,新增了许多功能: •对文件系统的访问提供了全面的支持 •提供了基于异步Channel的IO 这些新增的IO功能简称为 NIO.2,依然在java.nio包下. 早期的 ...

  8. java多线程 文件夹_java多线程读同一个文件

    java多线程同时读取一个文件,这个方法可行吗?不可行. 多线程能够提高效率是因为现在的cpu普遍是多核cpu, 多条线程可以在多个内核中同时执行来提高计算效率.但是计算机磁盘的磁头只有一个,即使多条 ...

  9. java 读文件夹_java怎么读取读取文件夹下的所有文件夹和文件?

    下是实现的代码:package com.borland.samples.welcome; import java.io.FileNotFoundException; import java.io.IO ...

  10. java web文件夹_JAVA WEB项目文件夹上传下载解决方案

    这里只写后端的代码,基本的思想就是,前端将文件分片,然后每次访问上传接口的时候,向后端传入参数:当前为第几块文件,和分片总数 下面直接贴代码吧,一些难懂的我大部分都加上注释了: 上传文件实体类: 看得 ...

最新文章

  1. Spring Boot整合Spring Data JPA操作数据
  2. 低版本系统兼容的ActionBar(四)添加Tab+添加自定义的Tab视图+Fragment
  3. 仿B站(一) 目的分析以及创建 WebAPI + Angular7 项目
  4. Android之事件总线EventBus详解
  5. Jsoup设置元素的文本内容
  6. 华为云PB级数据库GaussDB(for Redis)揭秘第七期:高斯Redis与强一致
  7. python爬虫:爬取某网站视频
  8. 弄了一个数学论坛,感觉不错,欢迎加入讨论
  9. [渝粤教育] 武汉科技大学 证券投资学 参考 资料
  10. I2S音频接口的理解
  11. 2021-2027全球与中国汽车传动轴联轴器市场现状及未来发展趋势
  12. DevExpress去除多国语言包
  13. 20172328的结对编程四则运算第二周-整体总结
  14. 九度OJ 1538 GrassLand密码
  15. simpleBGC32-软件代码开源
  16. 动手试试!手把手教你如何适配 iPhone X
  17. Zabbix监控之从zookeeper中获取Kafka消费进度和lag
  18. 对c语言课程的总结和认识,c语言课程设计总结8篇
  19. 案例5:Java大学生创新创业项目管理设计与实现任务书
  20. 【微信小程序】java配置环境变量步骤

热门文章

  1. 经过多次试验后第一个成功地实现 HTTPService 与 MXML 之间传递数据,ArrayCollection 与DataGrid 之间成功绑定...
  2. [转]用C#编写ActiveX控件
  3. 机器学习(7)——Logistic回归(从疝气病症预测病马的死亡率)
  4. 51单片机电子制作------篮球比赛计分器
  5. GDI+ is F**king unbelievable
  6. 路径 @/ ~/ / ./ ../
  7. 洛谷 P2341 [HAOI2006]受欢迎的牛 解题报告
  8. [android] 百度地图开发 (两).所在地的城市定位和城市POI搜索
  9. VS属性页的目录类型
  10. 判断 wp 是否是活跃页面