GZIP Multiple Files in Java Creating Tar Archive

GZIP is normally used to compress single files in GZIP format, if you want to compress multiple files using GZIP format in Java it is a two step process; first multiple files are archived into one with tar, then compressed with gzip to create a .tar.gz compressed archive. In this post we’ll see this whole process of compressing multiple files using gzip in Java by creating a tar file in Java and then gzip it thus creating a .tar.gz archive.

Gzip multiple files in Java

Jav program given here to archive multiple files into tar and then compress into GZIP uses Apache Commons Compress library which can be downloaded from this path- https://commons.apache.org/proper/commons-compress/download_compress.cgi

Version used here is commons-compress-1.18 so commons-compress-1.18.jar is added to the class path.

From Apache Commons Compress library two files are used for creating tar archive.

TarArchiveEntry– Represents an entry in a Tar archive. So all the directories and files which are compressed are added to tar archive using TarArchiveEntry.

TarArchiveOutputStream– This class has methods to put archive entries, and then write content of the files by writing to this stream. TarArchiveOutputStream wraps GZIPOutputStream in the program.

Java program – Create tar archive and Gzip multiple files

Directory structure used in the Java program is as given below, there is a parent directory test having two sub-directories docs and prints and four files-

In the program you need to traverse the directory structure to archive all files and directories. If it is a directory just archive that entry, in case of file apart from archiving that entry also write the content of the file to the stream.

Output for the entries in the tar archives-

As shown in the Archive Manager.

gzip mulitple files Java
That’s all for the topic GZIP Multiple Files in Java Creating Tar Archive. If something is missing or you have something to share about the topic please write a comment.


You may also like

  • How to Zip a Folder in Java
  • Generate PDF From XML in Java Using Apache FOP
  • Method Overloading in Java
  • throw Keyword in Java Exception Handling
  • Comparable Vs Comparator in Java
  • DelayQueue in Java
  • Leave a Reply

    Your email address will not be published. Required fields are marked *

    This site uses Akismet to reduce spam. Learn how your comment data is processed.