-
-
Save LikeJson/cd72d851c43c499a106d5ef4ff96a2e4 to your computer and use it in GitHub Desktop.
Unzipping file in android/kotlin
This file contains hidden or 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
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