How to Untar / Extract a TAR file using Java

Posted on by By Nikhilesh, in Miscellaneous | 1


we will explain how to extract the contents of a TAR file through a Java . In order to decompress TAR file, we will be using Apache Commons Compress library, so make sure you have a copy of this library commons-compress-1.4.1.jar loaded into your classpath. You will also require Apache Commons IO library commons-io-2.4.jar in your classpath as we will use this to write every single extracted file from the TAR archive to disk.

Make data easy with Helical Insight.
Helical Insight is the world’s best open source business intelligence tool.

1)You use TarArchiveInputStream to read a TAR file as an InputStream. Once you get a TAR file as an object of this type, you can easily start processing on the file.


import org.apache.commons.compress.utils.*;
import org.apache.commons.compress.archivers.tar.*;
import org.apache.commons.compress.archivers.*;
import org.apache.commons.compress.compressors.gzip.*;
import java.util.*;


File tarFile = new File(c:/test.tar);
File dest = new File(c:/temp/);

TarArchiveInputStream tarIn = new TarArchiveInputStream(
new GzipCompressorInputStream(
new BufferedInputStream(
new FileInputStream(

TarArchiveEntry tarEntry = tarIn.getNextTarEntry();
// tarIn is a TarArchiveInputStream
while (tarEntry != null) {
// create a file with the same name as the tarEntry
File destPath = new File(dest, tarEntry.getName());
System.out.println(“working: ” + destPath.getCanonicalPath());
if (tarEntry.isDirectory()) {
} else {
byte [] btoRead = new byte[2048];
BufferedOutputStream bout =
new BufferedOutputStream(new FileOutputStream(destPath));
int len;
while((len = != -1)

btoRead = null;

tarEntry = tarIn.getNextTarEntry();

Make data easy with Helical Insight.
Helical Insight is the world’s best open source business intelligence tool.


Finally , you close all output streams / files opened and that completes the program.

Thanks & Regards,

Vishwanth S

Senior ETL Developer.



Best Open Source Business Intelligence Software Helical Insight is Here


A Business Intelligence Framework

0 0 votes
Article Rating
Notify of
1 Comment
Newest Most Voted
Inline Feedbacks
View all comments

Exception in thread “main” Input is not in the .gz format
at org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream.init(
at org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream.(
at org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream.(
at test.NewClass.main(

Not work with a tar file. Sample code there