在java(JDK)中我們可以使用ZipOutputStream去創建zip壓縮檔案,(參考我之前寫的文章 使用java API進行zip遞回壓縮檔案夾以及解壓 ),也可以使用GZIPOutputStream去創建gzip(gz)壓縮檔案,但是java中沒有一種官方的API可以去創建tar.gz檔案,所以我們需要使用到第三方庫Apache Commons Compress去創建.tar.gz檔案,
在pom.xml中,我們可以通過如下的maven坐標引入commons-compress,
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.20</version>
</dependency>
解釋說明
- tar檔案準確的說是打包檔案,將檔案打包到一個tar檔案中,檔案名后綴是
.tar - Gzip是將檔案的存盤空間壓縮保存,檔案名后綴是
.gz tar.gz或.tgz通常是指將檔案打包到一個tar檔案中,并將它使用Gzip進行壓縮,
如果您閱讀完本文覺得對您有幫助的話,請給我一個贊,您的支持是我不竭的創作動力!
一、將兩個檔案打包到tar.gz
下面的這個例子是將2個檔案打包為tar.gz壓縮檔案,下文代碼中的流操作使用了try-with-resources語法,所以不用寫代碼手動的close流,
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.xml和file-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
二、將一個檔案夾壓縮為tar.gz
下面的例子將一個檔案夾,包含其子檔案夾的檔案或子目錄,打包為tar,并使用gzip進行壓縮,最終成為一個tar.gz打包壓縮檔案,
其核心原理是:使用到Files.walkFileTree依次遍歷檔案目錄樹中的檔案,將其一個一個的添加到TarArchiveOutputStream.輸出流,
@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();
}
}
三、解壓tar.gz壓縮檔案
下面一個例子說明如何解壓一個tar.gz檔案,具體內容請看代碼注釋,
@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;
}
歡迎關注我的博客,里面有很多精品合集
- 本文轉載注明出處(必須帶連接,不能只轉文字):字母哥博客,
覺得對您有幫助的話,幫我點贊、分享!您的支持是我不竭的創作動力! ,另外,筆者最近一段時間輸出了如下的精品內容,期待您的關注,
- 《手摸手教你學Spring Boot2.0》
- 《Spring Security-JWT-OAuth2一本通》
- 《實戰前后端分離RBAC權限管理系統》
- 《實戰SpringCloud微服務從青銅到王者》
- 《VUE深入淺出系列》
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/73384.html
標籤:Java
上一篇:Java Map 遍歷史上最全
下一篇:阿里的秒殺系統是怎么設計的?
