Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@Teqqles
Created January 20, 2016 13:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Teqqles/19ac70c1d302db6347c0 to your computer and use it in GitHub Desktop.
Save Teqqles/19ac70c1d302db6347c0 to your computer and use it in GitHub Desktop.
Quick and dirty decompression of a tar gzip file using Apache Commons Compress and Scala
import java.io.{File, FileOutputStream, BufferedOutputStream, InputStream}
import org.apache.commons.compress.archivers.tar.{TarArchiveEntry, TarArchiveInputStream}
import org.apache.commons.compress.compressors.gzip.GzipCompressorInputStream
object UnTarFile {
val BUFFER = 2048
def untar( in: InputStream, destinationDir: String ) {
def processTar( tarIn: TarArchiveInputStream ): Unit = {
def processFileInTar( dest: BufferedOutputStream ): Unit = {
val data = new Array[ Byte ]( BUFFER )
val count = tarIn.read( data, 0, BUFFER )
count match {
case -1 =>
dest.close( )
case _ =>
dest.write( data, 0, count )
processFileInTar( dest )
}
}
tarIn.getNextEntry.asInstanceOf[ TarArchiveEntry ]
match {
case null =>
case a: TarArchiveEntry if a.isDirectory =>
val f: File = new File( a.getName )
f.mkdirs( )
processTar( tarIn )
case a: TarArchiveEntry if a.isFile =>
println( "Extracting: " + a.getName )
val fos: FileOutputStream = new FileOutputStream( destinationDir + a.getName )
val dest: BufferedOutputStream = new BufferedOutputStream( fos,
BUFFER )
processFileInTar( dest )
processTar( tarIn )
case a: TarArchiveEntry => processTar( tarIn )
}
}
val gzIn: GzipCompressorInputStream = new GzipCompressorInputStream( in )
val tarIn: TarArchiveInputStream = new TarArchiveInputStream( gzIn )
processTar( tarIn )
tarIn.close( )
println( "untar completed successfully!!" )
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment