`

java压缩文件生成XXX.tar.gz压缩包

 
阅读更多
生成XXX.tar.gz压缩文件有两种方式,可以先打包后压缩,还可以打包压缩同时进行。

所用到的jar包见附件,若用maven,pom.xml文件内容如下:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.it.bill</groupId>
  <artifactId>bill_project.gi</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>bill_project.gi</name>
  <url>http://maven.apache.org</url>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  </properties>

  <dependencies>
    <dependency>
    	<groupId>junit</groupId>
    	<artifactId>junit</artifactId>
    	<version>4.10</version>
    </dependency>
    <dependency>
		<groupId>log4j</groupId>
		<artifactId>log4j</artifactId>
		<version>1.2.8</version>
	</dependency>
	<dependency>
		<groupId>javax.mail</groupId>
		<artifactId>mail</artifactId>
		<version>1.4</version>
	</dependency>
	<dependency>
		<groupId>commons-io</groupId>
		<artifactId>commons-io</artifactId>
		<version>2.4</version>
	</dependency>
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-compress</artifactId>
		<version>1.5</version>
	</dependency>
  </dependencies>
</project>





package com.bill;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.CompressorException;
import org.apache.commons.compress.compressors.CompressorOutputStream;
import org.apache.commons.compress.compressors.CompressorStreamFactory;
import org.apache.commons.compress.utils.IOUtils;
import org.apache.commons.io.FileUtils;

public class TestCompressSnapshotFiles {
  
  public static void main(String[] args) {
    try {
      String sourceFileDirPath = "C:/opt/webhost/pn/testCompressSnapshotXmlFiles/tempFileDir/";
      File sourceFileDir = new File(sourceFileDirPath);
      
      if (sourceFileDir.isDirectory()) {
        File[] sourceFileArr = sourceFileDir.listFiles(new FilenameFilter() {
          public boolean accept(File dir, String name) {
            return name.endsWith(".xml");
          }
        });
        
        /**
         * the first way, packaging before they are compressed
         */
        String targetFilePath = "C:/opt/webhost/pn/testCompressSnapshotXmlFiles/firstCompressedPackage.tar";
        File targetFile = new File(targetFilePath);
        File tarFile = packSnapshotXmlFiles(sourceFileArr, targetFile);
        compressSnapshotXmlFiles(tarFile);
        
        /**
         * the second way, packaging and compression at the same time
         */
        targetFilePath = "C:/opt/webhost/pn/testCompressSnapshotXmlFiles/secondCompressedPackage.tar.gz";
        targetFile = new File(targetFilePath);
        packAndCompressSnapshotXmlFiles(sourceFileArr, targetFile);
      } else {
        System.err.println("This is not folder: " + sourceFileDirPath);
      }
      
      System.out.println("----- Compress snapshot xml files end. ----");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  
  private static void packAndCompressSnapshotXmlFiles(File[] sourceFileArr,
      File targetFile) throws IOException, CompressorException {
    FileOutputStream fileOutputStream = null;
    CompressorOutputStream gzippedOut = null;
    TarArchiveOutputStream taos = null;
    
    try {
      fileOutputStream = FileUtils.openOutputStream(targetFile);
      
      gzippedOut = new CompressorStreamFactory().createCompressorOutputStream(
          CompressorStreamFactory.GZIP, fileOutputStream);
      
      taos = new TarArchiveOutputStream(gzippedOut);
      for (File perFile : sourceFileArr) {
        System.out.println(
            "current file name: " + perFile.getName() + ", length: "
                + perFile.length() / 1024);
        TarArchiveEntry tae = new TarArchiveEntry(perFile, perFile.getName());
        taos.putArchiveEntry(tae);
        taos.write(FileUtils.readFileToByteArray(perFile));
        taos.closeArchiveEntry();
      }
    } catch (IOException ioe) {
      throw ioe;
    } catch (CompressorException ce) {
      throw ce;
    } finally {
      if (taos != null) {
        try {
          taos.close();
        } catch (IOException e) {
        }
      }
      
      if (gzippedOut != null) {
        try {
          gzippedOut.close();
        } catch (IOException e) {
        }
      }
    }

  }

  private static void compressSnapshotXmlFiles(File tarFile) throws IOException {
    File target = new File(tarFile.getAbsolutePath() + ".gz");
    FileInputStream fis = null;
    GZIPOutputStream gzipOs = null;
    
    try {
      fis = new FileInputStream(tarFile);
      
      gzipOs = new GZIPOutputStream(new FileOutputStream(target));
      
      /*byte[] buffer = new byte[1024];
      int n = -1;
      while((n = fis.read(buffer)) != -1) {
        gzipOs.write(buffer, 0, n);
      }*/
      IOUtils.copy(fis, gzipOs);
      
      // delete the template tar file
      tarFile.deleteOnExit();
    } catch (FileNotFoundException fnfe) {
      System.err.println("file not found: " + tarFile.getAbsolutePath());
      throw fnfe;
    } catch (IOException ioe) {
      System.err.println("create gizp output stream fail");
      throw ioe;
    } finally {
      if (fis != null) {
        try {
          fis.close();
        } catch (IOException e) {
        }
      }
      
      if (gzipOs != null) {
        try {
          gzipOs.close();
        } catch (IOException e) {
        }
      }
    }
    
    
  }

  private static File packSnapshotXmlFiles(File[] sourceFileArr, File targetFile) throws IOException {
    FileOutputStream fos = null;
    TarArchiveOutputStream taos = null;
    try {
      fos = new FileOutputStream(targetFile);
      
      taos = new TarArchiveOutputStream(fos);
      
      for (File perFile : sourceFileArr) {
        System.out.println("current file name: " + perFile.getName() + ", length: " + perFile.length()/1024);
        taos.putArchiveEntry(new TarArchiveEntry(perFile, perFile.getName()));
        IOUtils.copy(new FileInputStream(perFile), taos);
        //taos.write(FileUtils.readFileToByteArray(perFile));
        taos.closeArchiveEntry();
      }
      
      //This line is very import, otherwise the compressed file can't successfully decompressed
      taos.finish();
    } catch (FileNotFoundException fnfe) {
      System.err.println("File not found: " + targetFile.getAbsolutePath());
      throw fnfe;
    } catch (IOException ioe) {
      System.err.println("put archive entry fail.");
      throw ioe;
    } finally {
      if (fos != null) {
        try {
          fos.close();
        } catch (IOException e) {
        }
      }
      
      if (taos != null) {
        try {
          taos.close();
        } catch (IOException e) {
        }
      }
    }
    
    return targetFile;
  }

}




分享到:
评论

相关推荐

    gcc.tar.gz(centos7离线安装包)

    linux 离线安装编译需要。 操作步骤: # gcc --version # tar xzvf gcc.tar.gz # cd gcc # rpm -Uvh *.rpm --nodeps --force # gcc --version gcc (GCC) 4.8.5 20150623 (Red Hat 4.8.5-39)

    redis-6.0.9.tar.gz.zip

    Linux版本,unzip xxx.tar.gz.zip后再tar -zxvf xxx.tar.gz,即可安装使用。 Redis(Remote Dictionary Server ),即远程字典服务,是一个开源的使用ANSI C语言编写、支持网络、可基于内存亦可持久化的日志型、Key-...

    node-v10.21.0-headers.tar.gz

    node 10.21.0 owt server 构建nodejs工具

    setuptools.tar.gz

    setuptools.tar.gz,在linux环境下使用pymssql模块之前需要进行安装。

    jre-8u251-windows-x64.tar.gz

    jdk-8u251-windows-x64.tar.gz 最新的windows-x64位压缩包 java8 官网最新版 分享给大家 希望能帮到大家

    glibc-2.11.1.tar.gz

    3.1 解压文件至一个指定目录 tar -zxvf ***glibc-2.11tar.gz /usr/libc/ 3.2 在该目录下编译需要指定一个build目录 /usr/libc/glibc-2.7/.configure --prefix /usr/libc/glibc-2.7-build//usr/libc/glibc-2.7-...

    jre-8u201-windows-x64.tar.gz

    jre-8u201-windows-x64.tar.gz,windows 64位jre资源,oracle官网

    cri-containerd-cni-1.6.8-linux-amd64.tar.gz

    containerd 是一个行业标准的容器运行时,强调简单性、健壮性、可移植性;继 Kubernetes、Prometheus、Envoy 和 CoreDNS 之后,于 2019 年 2 月 28 日,containerd 正式成为云原生计算基金会的毕业项目;...

    PyPI 官网下载 | xxx.server_api-0.32.5.tar.gz

    资源来自pypi官网。 资源全名:xxx.server_api-0.32.5.tar.gz

    cifar-10-batches-py.tar.gz

    务必记得放在/home/XXX/.keras/datasets/cifar-10-batches-py.tar.gz目录下(linux),或者 用户/.keras/datasets/cifar-10-batches-py.tar.gz(windows)

    inode-client.tar.gz

    pacman -U inode-client.xxx.pkg.tar.zx 启动后台服务: [root]# systemctl start iNodeAuthService ps 会看到AuthenMngService进程 添加用户组: [root]# usermod -G inode_h3c -a 启动软件: []$ xdg-...

    all-2.0.tar.gz,nessus离线插件包【2021.10.12】

    Nessus专业版插件(无扫描IP数限制),2021年10月12日的,离线升级方法:在nessus/sbin/路径下执行./nessuscli update all-2.0_xxx.tar.gz(xxx处按实际文件名写),然后重启nessusd服务,刷新web页面等待初始化完成...

    tensorflow_macos-0.1alpha3.tar.gz

    tensorflow_macos-0.1alpha3.tar.gz

    python3.6.tar.gz

    python3.6.5离线安装包,目前已经在CentOS6.5,CentOS7,RedHat上测试完美运行; 安装包已经包括以下python插件: asn1crypto==0.24.0 certifi==2016.2.28 ...安装离线包:cd python/bin && ./python3 pip3 install xxx

    xxx.tar.gz_BAD

    a very bad program created just do dowlnload a vitx

    liunx网卡驱动下载

    如果tar不支持j这个参数就先用 bzip2 -d xxx.tar.bz2 ...6.以.tar.gz/.tgz为扩展名的文件: #tar xvzf file.tar.gz 或 gzip -dc file.tar.gz | tar xvf - 7.以.tar.bz2为扩展名的文件: #tar xvIf file.tar.bz2

    jdk-8u152-linux-arm32-vfp-hflt.tar.gz.zip

    jdk-8u152-linux-arm32-vfp-hflt.tar.gz ;包含javafx的arm linux jdk . 此jdk比较难下载. 这里作为备份. Oracle官方已经声明 : jdk8u33以后的版本不再支持arm javafx. ;Linux下的java:cannot execute binary file:...

    hi3516aSensor驱动模板lm_xxx.tar.gz

    hi3516aSensor驱动模板,最简单的sensor驱动模板,只要将内部函数填满,基本都可以添加一个新的Sensor驱动。(下载注意不带ISP) 博客参考 http://blog.csdn.net/qq_21193563/article/details/79166452

    批处理文件(xxx.bat)转换为可执行文件(xxx.exe)的软件

    能将你做好的批处理文件(xxx.bat)转换成一个可执行文件(xxx.EXE),使它更像一个软件,更具保密性。

    node-v12.18.0-linux-x64.tar.xz 包含pm2离线包

    `tar -xvf node-v12.18.0-linux-x64.tar.xz` 2. `mv node-v12.18.0-linux-x64 nodejs` 3. 配置环境变量 `vim /home/用户名/.bash_profile` 1. 添加 `export NODE_HOME=/home/用户名/node/nodejs` 2. 添加 `PATH=...

Global site tag (gtag.js) - Google Analytics