In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use Java API to compress and decompress tar.gz files and folders". In the daily operation, it is believed that many people have doubts about how to use Java API to compress and decompress tar.gz files and folders. The editor consulted all kinds of materials and sorted out simple and useful operation methods. Hope to help you answer the question of "how to use Java API to compress and decompress tar.gz files and folders"! Next, please follow the editor to study!
In java (JDK) we can use ZipOutputStream to create zip compressed files, (refer to my previous article using java API for zip recursive folder compression and decompression), you can also use GZIPOutputStream to create gzip (gz) compressed files, but there is no official API in java to create tar.gz files. So we need to use the third-party library Apache Commons Compress to create .tar.gz files.
In pom.xml, we can introduce commons-compress with the following maven coordinates.
Org.apache.commons commons-compress 1.20
Explain and explain
A tar file is, to be exact, a package file, which is packaged into a tar file with a .tar suffix.
Gzip is to compress and save the storage space of a file, with the file name suffix .gz
Tar.gz or .tgz usually refers to packaging a file into a tar file and compressing it using Gzip.
If you find it helpful to you after reading this article, please give me a compliment, your support is my inexhaustible creative motivation!
First, package two files into tar.gz
The following example is to package 2 files as tar.gz compressed files. The flow operation in the following code uses the try-with-resources syntax, so there is no need to write code for manual close flows.
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 {/ / input file, compressed file Path path2 = Paths.get ("/ home/test/file-a.xml"); Path path3 = Paths.get ("/ home/test/file-b.txt"); List paths = Arrays.asList (path2, path3) / / output file compression result Path output = Paths.get ("/ home/test/output.tar.gz"); / / OutputStream output stream, BufferedOutputStream buffered output stream / / GzipCompressorOutputStream is gzip compressed output stream / / TarArchiveOutputStream tar packet output stream (including gzip compressed output stream) try (OutputStream fOut = Files.newOutputStream (output); BufferedOutputStream buffOut = new BufferedOutputStream (fOut); GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream (buffOut) TarArchiveOutputStream tOut = new TarArchiveOutputStream (gzOut) {/ / traversal file list for (Path path: paths) {/ / the file is not a directory or symbolic link if (! Files.isRegularFile (path)) {throw new IOException ("Support only file!") } / / put the file into the tar package and execute gzip compression TarArchiveEntry tarEntry = new TarArchiveEntry (path.toFile (), path.getFileName (). ToString ()); tOut.putArchiveEntry (tarEntry); Files.copy (path, tOut); tOut.closeArchiveEntry () After the for loop is completed, the finish-tar package output stream tOut.finish ();}
Package file-a.xml and file-b.txt into an output.tar file and compress the tar package using gzip. You can view the files contained in the tar package using the following command.
$tar-tvf / home/test/output.tar.gz-rw-r--r-- 0 file-a.xml-rw-r--r-- 0 23546 2020-08-17 12:07 file- 0 34 2020-08-17 12:36 file- b.txt II, compress a folder to tar.gz
The following example packages a folder containing files or subdirectories of its subfolders as tar and compresses it using gzip. Finally, it becomes a tar.gz packaged compressed file. The core principle is to use Files.walkFileTree to traverse the files in the file directory tree and add them one by one to TarArchiveOutputStream. Output stream.
[@ Test] (https://my.oschina.net/azibug)void testDirTarGzip () throws IOException {/ / compressed folder Path source = Paths.get ("/ home/test"); / / if not the folder throws an exception if (! Files.isDirectory (source)) {throw new IOException ("Please specify a folder") } / / the compressed output file name String tarFileName = "/ home/" + source.getFileName (). ToString () + ".tar.gz"; / / OutputStream output stream, BufferedOutputStream buffered output stream / / GzipCompressorOutputStream is gzip compressed output stream / / TarArchiveOutputStream tar packet output stream (including gzip compressed output stream) try (OutputStream fOut = Files.newOutputStream (Paths.get (tarFileName)); BufferedOutputStream buffOut = new BufferedOutputStream (fOut); GzipCompressorOutputStream gzOut = new GzipCompressorOutputStream (buffOut) TarArchiveOutputStream tOut = new TarArchiveOutputStream (gzOut) {/ / traverse the file directory tree Files.walkFileTree (source, new SimpleFileVisitor () {/ / when a file [@ Override] (https://my.oschina.net/u/1162528) public FileVisitResult visitFile (Path file) is accessed successfully BasicFileAttributes attributes) throws IOException {/ / determines whether the current traversal file is a symbolic link (shortcut) No packing compression processing if (attributes.isSymbolicLink ()) {return FileVisitResult.CONTINUE } / / get the name of the current traversal file Path targetFile = source.relativize (file); / / package the file TarArchiveEntry tarEntry = new TarArchiveEntry (file.toFile (), targetFile.toString ()); tOut.putArchiveEntry (tarEntry); Files.copy (file, tOut); tOut.closeArchiveEntry () / / continue next traversal file processing return FileVisitResult.CONTINUE;} / / current traversal file access failed [@ Override] (https://my.oschina.net/u/1162528) public FileVisitResult visitFileFailed (Path file, IOException exc) {System.err.printf ("unable to compress and package this file to tar.gz:% s%n%s%n", file, exc) Return FileVisitResult.CONTINUE;}}); / / after the for loop is completed, the finish-tar packet output stream tOut.finish ();}} 3. Extract the tar.gz compressed file
The following example shows how to extract a tar.gz file, see the code comments for details.
[@ Test] (https://my.oschina.net/azibug)void testDeCompressTarGzip () throws IOException {/ / extract the file Path source = Paths.get ("/ home/test/output.tar.gz"); / / where to extract Path target = Paths.get ("/ home/test2"); if (Files.notExists (source)) {throw new IOException ("the file you want to extract does not exist") } / / InputStream input stream, the following four streams read tar.gz into memory and operate / / BufferedInputStream buffer input stream / / GzipCompressorInputStream decompress input stream / / TarArchiveInputStream unpack tar packet input stream 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) {/ / get the extracted file directory and determine whether the file is damaged Path newPath = zipSlipProtect (entry, target); if (entry.isDirectory ()) {/ / create the extracted file directory Files.createDirectories (newPath) } else {/ / verify again whether the extracted file directory exists Path parent = newPath.getParent (); if (parent! = null) {if (Files.notExists (parent)) {Files.createDirectories (parent) }} / / input the extracted file to TarArchiveInputStream and output it to the disk newPath directory Files.copy (ti, newPath, StandardCopyOption.REPLACE_EXISTING);}} / / determine whether the compressed file is corrupted, and return to the extracted directory of the file 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 ("compressed file has been corrupted:" + entry.getName ());} return normalizePath;} at this point, the study on "how to use Java API for tar.gz file and folder compression and decompression" is over, hoping to solve everyone's doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.