這篇文章主要介紹“如何使用Java API進行tar.gz文件及文件夾壓縮解壓縮”,在日常操作中,相信很多人在如何使用Java API進行tar.gz文件及文件夾壓縮解壓縮問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”如何使用Java API進行tar.gz文件及文件夾壓縮解壓縮”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!
在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進行壓縮。
如果您閱讀完本文覺得對您有幫助的話,請給我一個贊,您的支持是我不竭的創作動力!
下面的這個例子是將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](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); //輸出文件壓縮結果 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包進行壓縮??梢允褂萌缦旅畈榭磘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
下面的例子將一個文件夾,包含其子文件夾的文件或子目錄,打包為tar,并使用gzip進行壓縮。最終成為一個tar.gz打包壓縮文件。 其核心原理是:使用到Files.walkFileTree
依次遍歷文件目錄樹中的文件,將其一個一個的添加到TarArchiveOutputStream
.輸出流。
[@Test](https://my.oschina.net/azibug) 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](https://my.oschina.net/u/1162528) 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](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循環完成之后,finish-tar包輸出流 tOut.finish(); } }
下面一個例子說明如何解壓一個tar.gz
文件,具體內容請看代碼注釋。
[@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輸入流,以下四個流將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; }
到此,關于“如何使用Java API進行tar.gz文件及文件夾壓縮解壓縮”的學習就結束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續學習更多相關知識,請繼續關注億速云網站,小編會繼續努力為大家帶來更多實用的文章!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。