Search code examples
javagziptarcompression

How to Compress/Decompress tar.gz files in java


Can anyone show me the correct way to compress and decompress tar.gzip files in java i've been searching but the most i can find is either zip or gzip(alone).


Solution

  • My favorite is plexus-archiver - see sources on GitHub.

    Another option is Apache commons-compress - (see mvnrepository).

    With plexus-utils, the code for unarchiving looks like this:

    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();
    

    Similar *Archiver classes are there for archiving.

    With Maven, you can use this dependency:

    <dependency>
      <groupId>org.codehaus.plexus</groupId>
      <artifactId>plexus-archiver</artifactId>
      <version>2.2</version>
    </dependency>