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

-
Facing issues? Have Questions? Post them here! I am happy to answer!
More Posts related to Java,
- Java equals method - Tutorial
- Unbound classpath container: JRE System Library [JavaSE-1.7]
- Spring Boot: @RequestBody not applicable to method
- Java 8: Steam map with Code Examples
- Java Program: Random Number Generator
- Java java.time.Clock class code examples [Java Date Time API]
- Fix: type argument is not within bounds of type-variable T
- [Fix] java.net.MalformedURLException: unknown protocol
- Java 7 addSuppression() and getSuppression() Exception Handling
- Convert Java Array to ArrayList Code Example
- How to Word-Warp Console logs in IntelliJ
- Ways Compare Dates in Java Programming with Examples
- Remove Trailing zeros BigDecimal Java
- CRUD operations in Spring Boot + JDBC
- [Java Threads] Should we extend Thread Class or implement Runnable interface
- Json Serialization and Deserialization using Java Jackson
- Create simple struts2 project using maven commands
- How to install Java OpenJDK 11 on Alpine Linux
- Unsupported major.minor version 52.0 in java
- Error: Can not find the tag library descriptor for
- Java: Convert String to Binary
- How to run Java Unit Test cases with Apache Maven?
- Java: Testing Private Methods in JUnit using reflection API Example
- Java JDBC Connection with MySQL Driver in VS Code + Troubleshooting
- Java Join Strings with Comma Separator
More Posts:
- JSP Hello World Program Tutorial with Eclipse and Tomcat Server - Java
- SharePoint Server 2016 error Microsoft Office Online Server 2016 cant be installed on the same machine as a Microsoft SharePoint Server product - SharePoint
- Alternatives for Notepad++ on Mac in 2021 - NotepadPlusPlus
- [fix] The declared package does not match the expected package - Java
- How to view the Eclipse error log - Eclipse
- Android : Error in http connection java.net.SocketException: Permission denied - Android
- Create Bootstrap carousel slider with Text - Bootstrap
- Git Config Command - A Deep Dive - Git