Created
October 6, 2013 12:41
-
-
Save ayosec/6853615 to your computer and use it in GitHub Desktop.
Extract files with Apache Commons Compress, from any archive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
libraryDependencies += "org.apache.commons" % "commons-compress" % "1.5" | |
scalaVersion := "2.10.2" |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package test | |
import org.apache.commons.compress.archivers.ArchiveStreamFactory | |
import org.apache.commons.compress.archivers.ArchiveInputStream | |
import org.apache.commons.compress.archivers.ArchiveEntry | |
import org.apache.commons.compress.compressors.CompressorStreamFactory | |
import scala.util.Try | |
import scala.util.Success | |
import scala.util.Failure | |
import java.io.InputStream | |
import java.io.FileInputStream | |
import java.io.BufferedInputStream | |
object Unpack { | |
def apply(path: String): Unit = { | |
def uncompress(input: BufferedInputStream): InputStream = | |
Try(new CompressorStreamFactory().createCompressorInputStream(input)) match { | |
case Success(i) => new BufferedInputStream(i) | |
case Failure(_) => input | |
} | |
def extract(input: InputStream): ArchiveInputStream = | |
new ArchiveStreamFactory().createArchiveInputStream(input) | |
val input = extract(uncompress(new BufferedInputStream(new FileInputStream(path)))) | |
def stream: Stream[ArchiveEntry] = input.getNextEntry match { | |
case null => Stream.empty | |
case entry => entry #:: stream | |
} | |
for(entry <- stream if !entry.isDirectory) { | |
println(s"${entry.getName} - ${entry.getSize} bytes") | |
} | |
} | |
} |
In java 6 like this:
ArchiveInputStream input;
try {
input = new ArchiveStreamFactory().createArchiveInputStream(new CompressorStreamFactory().createCompressorInputStream(new BufferedInputStream(new FileInputStream(filePath))));
ArchiveEntry entry;
while ((entry = input.getNextEntry()) != null) {
String name = entry.getName();
// . . .
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, How I Use this code?
thanks in advance