In order to compress files and folders as a tar.gz file in Java we can make use of the Apache Commons Compress dependency.
Maven Dependency:
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.23.0</version>
</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;
import java.io.*;
import java.util.zip.Deflater;
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);
tarArchiveOutputStream.setBigNumberMode(TarArchiveOutputStream.BIGNUMBER_STAR);
tarArchiveOutputStream.setLongFileMode(TarArchiveOutputStream.LONGFILE_GNU);
File sourceDir = new File(sourceDirPath);
addFilesToTar(sourceDir, tarOut, "");
tarOut.finish();
tarOut.close();
System.out.println("File created.. : " + tarGzFilePath);
} catch (IOException e) {
e.printStackTrace();
}
}
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());
entry.setSize(file.length());
tarOut.putArchiveEntry(entry);
try (FileInputStream fis = new FileInputStream(file)) {
byte[] buffer = new byte[1024];
int read;
while ((read = fis.read(buffer)) != -1) {
tarOut.write(buffer, 0, read);
}
}
tarOut.closeArchiveEntry();
}
}
}
}
}
Know More:

Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!