热门标签 | HotTags
当前位置:  开发笔记 > 运维 > 正文

JavaGZip基于磁盘实现压缩和解压的方法

这篇文章主要介绍了JavaGZip基于磁盘实现压缩和解压,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考需要的朋友可以参考下

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


推荐阅读
  • 一、Hadoop来历Hadoop的思想来源于Google在做搜索引擎的时候出现一个很大的问题就是这么多网页我如何才能以最快的速度来搜索到,由于这个问题Google发明 ... [详细]
  • 本文介绍了在Linux下安装和配置Kafka的方法,包括安装JDK、下载和解压Kafka、配置Kafka的参数,以及配置Kafka的日志目录、服务器IP和日志存放路径等。同时还提供了单机配置部署的方法和zookeeper地址和端口的配置。通过实操成功的案例,帮助读者快速完成Kafka的安装和配置。 ... [详细]
  • Skywalking系列博客1安装单机版 Skywalking的快速安装方法
    本文介绍了如何快速安装单机版的Skywalking,包括下载、环境需求和端口检查等步骤。同时提供了百度盘下载地址和查询端口是否被占用的命令。 ... [详细]
  • Linux服务器密码过期策略、登录次数限制、私钥登录等配置方法
    本文介绍了在Linux服务器上进行密码过期策略、登录次数限制、私钥登录等配置的方法。通过修改配置文件中的参数,可以设置密码的有效期、最小间隔时间、最小长度,并在密码过期前进行提示。同时还介绍了如何进行公钥登录和修改默认账户用户名的操作。详细步骤和注意事项可参考本文内容。 ... [详细]
  • 学习SLAM的女生,很酷
    本文介绍了学习SLAM的女生的故事,她们选择SLAM作为研究方向,面临各种学习挑战,但坚持不懈,最终获得成功。文章鼓励未来想走科研道路的女生勇敢追求自己的梦想,同时提到了一位正在英国攻读硕士学位的女生与SLAM结缘的经历。 ... [详细]
  • 本文介绍了在Win10上安装WinPythonHadoop的详细步骤,包括安装Python环境、安装JDK8、安装pyspark、安装Hadoop和Spark、设置环境变量、下载winutils.exe等。同时提醒注意Hadoop版本与pyspark版本的一致性,并建议重启电脑以确保安装成功。 ... [详细]
  • 图解redis的持久化存储机制RDB和AOF的原理和优缺点
    本文通过图解的方式介绍了redis的持久化存储机制RDB和AOF的原理和优缺点。RDB是将redis内存中的数据保存为快照文件,恢复速度较快但不支持拉链式快照。AOF是将操作日志保存到磁盘,实时存储数据但恢复速度较慢。文章详细分析了两种机制的优缺点,帮助读者更好地理解redis的持久化存储策略。 ... [详细]
  • 本文介绍了在Mac上搭建php环境后无法使用localhost连接mysql的问题,并通过将localhost替换为127.0.0.1或本机IP解决了该问题。文章解释了localhost和127.0.0.1的区别,指出了使用socket方式连接导致连接失败的原因。此外,还提供了相关链接供读者深入了解。 ... [详细]
  • 计算机存储系统的层次结构及其优势
    本文介绍了计算机存储系统的层次结构,包括高速缓存、主存储器和辅助存储器三个层次。通过分层存储数据可以提高程序的执行效率。计算机存储系统的层次结构将各种不同存储容量、存取速度和价格的存储器有机组合成整体,形成可寻址存储空间比主存储器空间大得多的存储整体。由于辅助存储器容量大、价格低,使得整体存储系统的平均价格降低。同时,高速缓存的存取速度可以和CPU的工作速度相匹配,进一步提高程序执行效率。 ... [详细]
  • Android系统移植与调试之如何修改Android设备状态条上音量加减键在横竖屏切换的时候的显示于隐藏
    本文介绍了如何修改Android设备状态条上音量加减键在横竖屏切换时的显示与隐藏。通过修改系统文件system_bar.xml实现了该功能,并分享了解决思路和经验。 ... [详细]
  • 本文介绍了一些Java开发项目管理工具及其配置教程,包括团队协同工具worktil,版本管理工具GitLab,自动化构建工具Jenkins,项目管理工具Maven和Maven私服Nexus,以及Mybatis的安装和代码自动生成工具。提供了相关链接供读者参考。 ... [详细]
  • 本文由编程笔记#小编为大家整理,主要介绍了StartingzookeeperFAILEDTOSTART相关的知识,希望对你有一定的参考价值。下载路径:https://ar ... [详细]
  • CEPH LIO iSCSI Gateway及其使用参考文档
    本文介绍了CEPH LIO iSCSI Gateway以及使用该网关的参考文档,包括Ceph Block Device、CEPH ISCSI GATEWAY、USING AN ISCSI GATEWAY等。同时提供了多个参考链接,详细介绍了CEPH LIO iSCSI Gateway的配置和使用方法。 ... [详细]
  • 本文介绍了使用Spark实现低配版高斯朴素贝叶斯模型的原因和原理。随着数据量的增大,单机上运行高斯朴素贝叶斯模型会变得很慢,因此考虑使用Spark来加速运行。然而,Spark的MLlib并没有实现高斯朴素贝叶斯模型,因此需要自己动手实现。文章还介绍了朴素贝叶斯的原理和公式,并对具有多个特征和类别的模型进行了讨论。最后,作者总结了实现低配版高斯朴素贝叶斯模型的步骤。 ... [详细]
  • 本文讨论了读书的目的以及学习算法的重要性,并介绍了两个算法:除法速算和约瑟夫环的数学算法。同时,通过具体的例子和推理,解释了为什么x=x+k序列中的第一个人的位置为k,以及序列2和序列3的关系。通过学习算法,可以提高思维能力和解决问题的能力。 ... [详细]
author-avatar
沉沉浮浮触涙水
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有