How to create a tar.gz file using Java

In order to compress files and folders as a tar.gz file in Java we can make use of the Apache Commons Compress dependency.

Apache Commons Compress API can be used to compression and archive formats such as bzip2, gzip, pack200, lzma, xz, Snappy, traditional Unix Compress, DEFLATE, DEFLATE64, LZ4, Brotli, Zstandard and ar, cpio, jar, tar, zip, dump, 7z, arj.

Maven Dependency:


Gradle Dependency:

implementation group: 'org.apache.commons', name: 'commons-compress', version: '1.23.0'

Code Example:

import org.apache.commons.compress.archivers.tar.TarArchiveEntry;
import org.apache.commons.compress.archivers.tar.TarArchiveOutputStream;
import org.apache.commons.compress.compressors.gzip.GzipCompressorOutputStream;


public class TarGzCreatorWithJava {

    public static void main(String[] args) {
        String sourceDirPath = "/data";
        String tarGzFilePath = "/data/data.tar.gz";

        try {
            var fileOutputStream = new FileOutputStream(tarGzFilePath);
            var gzipCompressorOutputStream = new GzipCompressorOutputStream(fileOutputStream);
            var tarArchiveOutputStream = new TarArchiveOutputStream(gzipCompressorOutputStream);

            File sourceDir = new File(sourceDirPath);
            addFilesToTar(sourceDir, tarOut, "");


            System.out.println("File created.. : " + tarGzFilePath);
        } catch (IOException e) {

    private static void addFilesToTar(File source, TarArchiveOutputStream tarOut, String parentDir) throws IOException {
        File[] files = source.listFiles();
        if (files != null) {
            for (File file : files) {
                if (file.isDirectory()) {
                    addFilesToTar(file, tarOut, parentDir + file.getName() + "/");
                } else {
                    TarArchiveEntry entry = new TarArchiveEntry(parentDir + file.getName());

                    try (FileInputStream fis = new FileInputStream(file)) {
                        byte[] buffer = new byte[1024];
                        int read;
                        while ((read = != -1) {
                            tarOut.write(buffer, 0, read);

Created a tar.gz file using Java

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap