您好,登錄后才能下訂單哦!
這篇文章主要介紹“如何使用Java API進(jìn)行tar.gz文件及文件夾壓縮解壓縮”,在日常操作中,相信很多人在如何使用Java API進(jìn)行tar.gz文件及文件夾壓縮解壓縮問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何使用Java API進(jìn)行tar.gz文件及文件夾壓縮解壓縮”的疑惑有所幫助!接下來,請跟著小編一起來學(xué)習(xí)吧!
在java(JDK)中我們可以使用ZipOutputStream
去創(chuàng)建zip壓縮文件,(參考我之前寫的文章 使用java API進(jìn)行zip遞歸壓縮文件夾以及解壓 ),也可以使用GZIPOutputStream
去創(chuàng)建gzip(gz)壓縮文件,但是java中沒有一種官方的API可以去創(chuàng)建tar.gz
文件。所以我們需要使用到第三方庫Apache Commons Compress去創(chuàng)建.tar.gz
文件。
在pom.xml中,我們可以通過如下的maven坐標(biāo)引入commons-compress。
<dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-compress</artifactId> <version>1.20</version> </dependency>
解釋說明
tar文件準(zhǔn)確的說是打包文件,將文件打包到一個(gè)tar文件中,文件名后綴是.tar
Gzip是將文件的存儲(chǔ)空間壓縮保存,文件名后綴是.gz
tar.gz
或.tgz
通常是指將文件打包到一個(gè)tar文件中,并將它使用Gzip進(jìn)行壓縮。
如果您閱讀完本文覺得對您有幫助的話,請給我一個(gè)贊,您的支持是我不竭的創(chuàng)作動(dòng)力!
下面的這個(gè)例子是將2個(gè)文件打包為tar.gz
壓縮文件。下文代碼中的流操作使用了try-with-resources語法,所以不用寫代碼手動(dòng)的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](https://my.oschina.net/azibug) void testFilesTarGzip() throws IOException { //輸入文件,被壓縮文件 Path path2 = Paths.get("/home/test/file-a.xml"); Path path3 = Paths.get("/home/test/file-b.txt"); List<Path> paths = Arrays.asList(path2, path3); //輸出文件壓縮結(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對這個(gè)tar包進(jìn)行壓縮??梢允褂萌缦旅畈榭磘ar包里面包含的文件。
$ 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
下面的例子將一個(gè)文件夾,包含其子文件夾的文件或子目錄,打包為tar,并使用gzip進(jìn)行壓縮。最終成為一個(gè)tar.gz打包壓縮文件。 其核心原理是:使用到Files.walkFileTree
依次遍歷文件目錄樹中的文件,將其一個(gè)一個(gè)的添加到TarArchiveOutputStream
.輸出流。
[@Test](https://my.oschina.net/azibug) void testDirTarGzip() throws IOException { // 被壓縮打包的文件夾 Path source = Paths.get("/home/test"); //如果不是文件夾拋出異常 if (!Files.isDirectory(source)) { throw new IOException("請指定一個(gè)文件夾"); } //壓縮之后的輸出文件名稱 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>() { //當(dāng)成功訪問到一個(gè)文件 [@Override](https://my.oschina.net/u/1162528) public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) throws IOException { // 判斷當(dāng)前遍歷文件是不是符號鏈接(快捷方式),不做打包壓縮處理 if (attributes.isSymbolicLink()) { return FileVisitResult.CONTINUE; } //獲取當(dāng)前遍歷文件名稱 Path targetFile = source.relativize(file); //將該文件打包壓縮 TarArchiveEntry tarEntry = new TarArchiveEntry( file.toFile(), targetFile.toString()); tOut.putArchiveEntry(tarEntry); Files.copy(file, tOut); tOut.closeArchiveEntry(); //繼續(xù)下一個(gè)遍歷文件處理 return FileVisitResult.CONTINUE; } //當(dāng)前遍歷文件訪問失敗 [@Override](https://my.oschina.net/u/1162528) 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(); } }
下面一個(gè)例子說明如何解壓一個(gè)tar.gz
文件,具體內(nèi)容請看代碼注釋。
[@Test](https://my.oschina.net/azibug) 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輸入流,以下四個(gè)流將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 { //再次校驗(yàn)解壓文件目錄是否存在 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)于“如何使用Java API進(jìn)行tar.gz文件及文件夾壓縮解壓縮”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)砀鄬?shí)用的文章!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。