Skip to content

Instantly share code, notes, and snippets.

@LikeJson
Forked from NitinPraksash9911/UnzipUtils.kt
Created August 21, 2021 13:56
Show Gist options
  • Save LikeJson/cd72d851c43c499a106d5ef4ff96a2e4 to your computer and use it in GitHub Desktop.
Save LikeJson/cd72d851c43c499a106d5ef4ff96a2e4 to your computer and use it in GitHub Desktop.
Unzipping file in android/kotlin
import java.io.*
import java.util.zip.ZipFile
/**
* UnzipUtils class extracts files and sub-directories of a standard zip file to
* a destination directory.
*
*/
object UnzipUtils {
/**
* @param zipFilePath
* @param destDirectory
* @throws IOException
*/
@Throws(IOException::class)
fun unzip(zipFilePath: File, destDirectory: String) {
val destDir = File(destDirectory)
if (!destDir.exists()) {
destDir.mkdir()
}
ZipFile(zipFilePath).use { zip ->
zip.entries().asSequence().forEach { entry ->
zip.getInputStream(entry).use { input ->
val filePath = destDirectory + File.separator + entry.name
if (!entry.isDirectory) {
// if the entry is a file, extracts it
extractFile(input, filePath)
} else {
// if the entry is a directory, make the directory
val dir = File(filePath)
dir.mkdir()
}
}
}
}
}
/**
* Extracts a zip entry (file entry)
* @param inputStream
* @param destFilePath
* @throws IOException
*/
@Throws(IOException::class)
private fun extractFile(inputStream: InputStream, destFilePath: String) {
val bos = BufferedOutputStream(FileOutputStream(destFilePath))
val bytesIn = ByteArray(BUFFER_SIZE)
var read: Int
while (inputStream.read(bytesIn).also { read = it } != -1) {
bos.write(bytesIn, 0, read)
}
bos.close()
}
/**
* Size of the buffer to read/write data
*/
private const val BUFFER_SIZE = 4096
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment