在java(JDK)中我們可以使用ZipOutputStream
去創(chuàng)建zip壓縮文件掏父,(參考我之前寫的文章 使用java API進行zip遞歸壓縮文件夾以及解壓 ),也可以使用GZIPOutputStream
去創(chuàng)建gzip(gz)壓縮文件兼都,但是java中沒有一種官方的API可以去創(chuàng)建tar.gz
文件旨涝。所以我們需要使用到第三方庫Apache Commons Compress去創(chuàng)建.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進行壓縮赏酥。
如果您閱讀完本文覺得對您有幫助的話,請給我一個贊谆构,您的支持是我不竭的創(chuàng)作動力裸扶!
一、將兩個文件打包到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);
//輸出文件壓縮結(jié)果
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包,并執(zhí)行g(shù)zip壓縮
TarArchiveEntry tarEntry = new TarArchiveEntry(
path.toFile(),
path.getFileName().toString());
tOut.putArchiveEntry(tarEntry);
Files.copy(path, tOut);
tOut.closeArchiveEntry();
}
//for循環(huán)完成之后猪杭,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();
//繼續(xù)下一個遍歷文件處理
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循環(huán)完成之后津坑,finish-tar包輸出流
tOut.finish();
}
}
三妙蔗、解壓tar.gz壓縮文件
下面一個例子說明如何解壓一個tar.gz
文件,具體內(nèi)容請看代碼注釋疆瑰。
@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讀取到內(nèi)存并操作
//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()) {
//創(chuàng)建解壓文件目錄
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;
}
歡迎關(guān)注我的博客,里面有很多精品合集
- 本文轉(zhuǎn)載注明出處(必須帶連接孵睬,不能只轉(zhuǎn)文字):字母哥博客播歼。
覺得對您有幫助的話,幫我點贊掰读、分享秘狞!您的支持是我不竭的創(chuàng)作動力! 蹈集。另外烁试,筆者最近一段時間輸出了如下的精品內(nèi)容,期待您的關(guān)注拢肆。