Skip to content

Instantly share code, notes, and snippets.

@nkhalasi
Last active March 4, 2017 03:56
Show Gist options
  • Select an option

  • Save nkhalasi/0f6ea78bf41f9a19f385c40f9cf2b00a to your computer and use it in GitHub Desktop.

Select an option

Save nkhalasi/0f6ea78bf41f9a19f385c40f9cf2b00a to your computer and use it in GitHub Desktop.
Shortest zip extraction code I have ever written
import java.io.FileOutputStream
import java.nio.file.Path
import java.util.zip.ZipInputStream
tailrec fun ZipInputStream.extract(outputDir: Path, extractedFiles: List<Path>) : List<Path> =
nextEntry?.let { ze ->
val zf = outputDir.resolve(ze.name).apply {
toFile().outputStream().use {
fileForZipEntry(it)
}
}
extract(outputDir, extractedFiles+listOf(zf))
} ?: extractedFiles
tailrec fun ZipInputStream.fileForZipEntry(fos: FileOutputStream) {
val buffer = ByteArray(1024)
val len = read(buffer)
if (len > 0) {
fos.write(buffer, 0, len)
fileForZipEntry(fos)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment