使用Java API進行tar.gz文件及文件夾壓縮解壓縮

在java(JDK)中咱們可使用ZipOutputStream去建立zip壓縮文件,(參考我以前寫的文章 使用java API進行zip遞歸壓縮文件夾以及解壓 ),也可使用GZIPOutputStream去建立gzip(gz)壓縮文件,可是java中沒有一種官方的API能夠去建立tar.gz文件。因此咱們須要使用到第三方庫Apache Commons Compress去建立.tar.gz文件。html

在pom.xml中,咱們能夠經過以下的maven座標引入commons-compress。vue

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.20</version>
</dependency>

解釋說明java

  1. tar文件準確的說是打包文件,將文件打包到一個tar文件中,文件名後綴是.tar
  2. Gzip是將文件的存儲空間壓縮保存,文件名後綴是.gz
  3. tar.gz.tgz一般是指將文件打包到一個tar文件中,並將它使用Gzip進行壓縮。

若是您閱讀完本文以爲對您有幫助的話,請給我一個贊,您的支持是我不竭的創做動力!spring

1、將兩個文件打包到tar.gz

下面的這個例子是將2個文件打包爲tar.gz壓縮文件。下文代碼中的流操做使用了try-with-resources語法,因此不用寫代碼手動的close流。apache

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;
import org.junit.jupiter.api.Test;

import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;

public class TarGzTest {

  @Test
  void testFilesTarGzip() throws IOException {
    //輸入文件,被壓縮文件
    Path path1 = Paths.get("/home/test/file-a.xml");
    Path path2 = Paths.get("/home/test/file-b.txt");
    List<Path> paths = Arrays.asList(path1, path2);

    //輸出文件壓縮結果
    Path output = Paths.get("/home/test/output.tar.gz");

    //OutputStream輸出流、BufferedOutputStream緩衝輸出流
    //GzipCompressorOutputStream是gzip壓縮輸出流
    //TarArchiveOutputStream打tar包輸出流(包含gzip壓縮輸出流)
    try (OutputStream fOut = Files.newOutputStream(output);
         BufferedOutputStream buffOut = new BufferedOutputStream(fOut);
         GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(buffOut);
         TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut)) {

      //遍歷文件list
      for (Path path : paths) {
        //該文件不是目錄或者符號連接
        if (!Files.isRegularFile(path)) {
          throw new IOException("Support only file!");
        }
        //將該文件放入tar包,並執行gzip壓縮
        TarArchiveEntry tarEntry = new TarArchiveEntry(
                path.toFile(),
                path.getFileName().toString());

        tOut.putArchiveEntry(tarEntry);
        Files.copy(path, tOut);

        tOut.closeArchiveEntry();
      }
      //for循環完成以後,finish-tar包輸出流
      tOut.finish();
    }
  }
}

file-a.xmlfile-b.txt打包到output.tar文件中,並使用gzip對這個tar包進行壓縮。可使用以下命令查看tar包裏面包含的文件。後端

$ tar -tvf /home/test/output.tar.gz
-rw-r--r-- 0/0          23546 2020-08-17 12:07 file-a.xml
-rw-r--r-- 0/0              34  2020-08-17 12:36 file-b.txt

2、將一個文件夾壓縮爲tar.gz

下面的例子將一個文件夾,包含其子文件夾的文件或子目錄,打包爲tar,並使用gzip進行壓縮。最終成爲一個tar.gz打包壓縮文件。
其核心原理是:使用到Files.walkFileTree依次遍歷文件目錄樹中的文件,將其一個一個的添加到TarArchiveOutputStream.輸出流。api

@Test
void testDirTarGzip() throws IOException {
  // 被壓縮打包的文件夾
  Path source = Paths.get("/home/test");
  //若是不是文件夾拋出異常
  if (!Files.isDirectory(source)) {
    throw new IOException("請指定一個文件夾");
  }

  //壓縮以後的輸出文件名稱
  String tarFileName = "/home/" + source.getFileName().toString() + ".tar.gz";

  //OutputStream輸出流、BufferedOutputStream緩衝輸出流
  //GzipCompressorOutputStream是gzip壓縮輸出流
  //TarArchiveOutputStream打tar包輸出流(包含gzip壓縮輸出流)
  try (OutputStream fOut = Files.newOutputStream(Paths.get(tarFileName));
       BufferedOutputStream buffOut = new BufferedOutputStream(fOut);
       GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream(buffOut);
       TarArchiveOutputStream tOut = new TarArchiveOutputStream(gzOut)) {
    //遍歷文件目錄樹
    Files.walkFileTree(source, new SimpleFileVisitor<Path>() {

      //當成功訪問到一個文件
      @Override
      public FileVisitResult visitFile(Path file,
                                       BasicFileAttributes attributes) throws IOException {

        // 判斷當前遍歷文件是否是符號連接(快捷方式),不作打包壓縮處理
        if (attributes.isSymbolicLink()) {
          return FileVisitResult.CONTINUE;
        }

        //獲取當前遍歷文件名稱
        Path targetFile = source.relativize(file);

        //將該文件打包壓縮
        TarArchiveEntry tarEntry = new TarArchiveEntry(
                file.toFile(), targetFile.toString());
        tOut.putArchiveEntry(tarEntry);
        Files.copy(file, tOut);
        tOut.closeArchiveEntry();
        //繼續下一個遍歷文件處理
        return FileVisitResult.CONTINUE;
      }

      //當前遍歷文件訪問失敗
      @Override
      public FileVisitResult visitFileFailed(Path file, IOException exc) {
        System.err.printf("沒法對該文件壓縮打包爲tar.gz : %s%n%s%n", file, exc);
        return FileVisitResult.CONTINUE;
      }

    });
    //for循環完成以後,finish-tar包輸出流
    tOut.finish();
  }
}

3、解壓tar.gz壓縮文件

下面一個例子說明如何解壓一個tar.gz文件,具體內容請看代碼註釋。springboot

@Test
void testDeCompressTarGzip() throws IOException {
  //解壓文件
  Path source = Paths.get("/home/test/output.tar.gz");
  //解壓到哪
  Path target = Paths.get("/home/test2");
  
  if (Files.notExists(source)) {
    throw new IOException("您要解壓的文件不存在");
  }

  //InputStream輸入流,如下四個流將tar.gz讀取到內存並操做
  //BufferedInputStream緩衝輸入流
  //GzipCompressorInputStream解壓輸入流
  //TarArchiveInputStream解tar包輸入流
  try (InputStream fi = Files.newInputStream(source);
       BufferedInputStream bi = new BufferedInputStream(fi);
       GzipCompressorInputStream gzi = new GzipCompressorInputStream(bi);
       TarArchiveInputStream ti = new TarArchiveInputStream(gzi)) {

    ArchiveEntry entry;
    while ((entry = ti.getNextEntry()) != null) {

      //獲取解壓文件目錄,並判斷文件是否損壞
      Path newPath = zipSlipProtect(entry, target);
      
      if (entry.isDirectory()) {
        //建立解壓文件目錄
        Files.createDirectories(newPath);
      } else {
        //再次校驗解壓文件目錄是否存在
        Path parent = newPath.getParent();
        if (parent != null) {
          if (Files.notExists(parent)) {
            Files.createDirectories(parent);
          }
        }
        // 將解壓文件輸入到TarArchiveInputStream,輸出到磁盤newPath目錄
        Files.copy(ti, newPath, StandardCopyOption.REPLACE_EXISTING);

      }
    }
  }
  
}

//判斷壓縮文件是否被損壞,並返回該文件的解壓目錄
private  Path zipSlipProtect(ArchiveEntry entry,Path targetDir)
        throws IOException {

  Path targetDirResolved = targetDir.resolve(entry.getName());
  Path normalizePath = targetDirResolved.normalize();

  if (!normalizePath.startsWith(targetDir)) {
    throw new IOException("壓縮文件已被損壞: " + entry.getName());
  }

  return normalizePath;
}

歡迎關注個人博客,裏面有不少精品合集

  • 本文轉載註明出處(必須帶鏈接,不能只轉文字):字母哥博客

以爲對您有幫助的話,幫我點贊、分享!您的支持是我不竭的創做動力! 。另外,筆者最近一段時間輸出了以下的精品內容,期待您的關注。bash

相關文章
相關標籤/搜索