如何在java中压缩/解压缩tar.gz文件

任何人都可以告诉我压缩和解压缩java中的tar.gzip文件的正确方法我一直在搜索,但我能找到的最多是zip或gzip(单独)。

我最喜欢的是plexus-archiver – 请参阅GitHub上的消息来源。

另一种选择是Apache commons-compress – (参见mvnrepository )。

使用plexus-utils,unarchiving的代码如下所示:

final TarGZipUnArchiver ua = new TarGZipUnArchiver(); // Logging - as @Akom noted, logging is mandatory in newer versions, so you can use a code like this to configure it: ConsoleLoggerManager manager = new ConsoleLoggerManager(); manager.initialize(); ua.enableLogging(manager.getLoggerForComponent("bla")); // -- end of logging part ua.setSourceFile(sourceFile); destDir.mkdirs(); ua.setDestDirectory(destDir); ua.extract(); 

类似的* Archiver类可用于存档。

使用Maven,您可以使用此依赖项 :

  org.codehaus.plexus plexus-archiver 2.2  

我已经编写了一个名为jarchivelib的 commons-compress包装器,它可以很容易地从File对象中提取或压缩。

示例代码如下所示:

 File archive = new File("/home/thrau/archive.tar.gz"); File destination = new File("/home/thrau/archive/"); Archiver archiver = ArchiverFactory.createArchiver("tar", "gz"); archiver.extract(archive, destination); 

根据我的经验, Apache Compress比Plexus Archiver更成熟,特别是因为像http://jira.codehaus.org/browse/PLXCOMP-131这样的问题。

我相信Apache Compress也有更多的活动。

要提取.tar.gz格式的内容,我成功使用了apache commons-compress (’org.apache.commons:commons-compress:1.12’)。 看看这个示例方法:

 public void extractTarGZ(InputStream in) { GzipCompressorInputStream gzipIn = new GzipCompressorInputStream(in); try (TarArchiveInputStream tarIn = new TarArchiveInputStream(gzipIn)) { TarArchiveEntry entry; while ((entry = (TarArchiveEntry) tarIn.getNextEntry()) != null) { /** If the entry is a directory, create the directory. **/ if (entry.isDirectory()) { File f = new File(entry.getName()); boolean created = f.mkdir(); if (!created) { System.out.printf("Unable to create directory '%s', during extraction of archive contents.\n", f.getAbsolutePath()); } } else { int count; byte data[] = new byte[BUFFER_SIZE]; FileOutputStream fos = new FileOutputStream(entry.getName(), false); try (BufferedOutputStream dest = new BufferedOutputStream(fos, BUFFER_SIZE)) { while ((count = tarIn.read(data, 0, BUFFER_SIZE)) != -1) { dest.write(data, 0, count); } } } } System.out.println("Untar completed successfully!"); } } 

它适用于我,使用GZIPInputStream , https: GZIPInputStream

如果您计划在Linux上进行压缩/解压缩,可以调用shell命令行:

 Files.createDirectories(Paths.get(target)); ProcessBuilder builder = new ProcessBuilder(); builder.command("sh", "-c", String.format("tar xfz %s -C %s", tarGzPathLocation, target)); builder.directory(new File("/tmp")); Process process = builder.start(); int exitCode = process.waitFor(); assert exitCode == 0;