Rewrite ZipUtils in Kotlin

This commit is contained in:
topjohnwu
2019-05-03 04:10:27 -04:00
parent d3f5f5ee59
commit 8b7144c986
3 changed files with 48 additions and 67 deletions
@@ -0,0 +1,46 @@
package com.topjohnwu.magisk.utils
import com.topjohnwu.superuser.io.SuFile
import com.topjohnwu.superuser.io.SuFileOutputStream
import java.io.File
import java.io.IOException
import java.io.InputStream
import java.util.zip.ZipEntry
import java.util.zip.ZipInputStream
@Throws(IOException::class)
@JvmOverloads
fun unzip(zip: File, folder: File, path: String = "", junkPath: Boolean = false) {
zip.inputStream().buffered().use {
unzip(it, folder, path, junkPath)
}
}
@Throws(IOException::class)
fun unzip(zip: InputStream, folder: File, path: String, junkPath: Boolean) {
try {
val zin = ZipInputStream(zip)
var entry: ZipEntry
while (true) {
entry = zin.nextEntry ?: break
if (!entry.name.startsWith(path) || entry.isDirectory) {
// Ignore directories, only create files
continue
}
val name = if (junkPath)
entry.name.substring(entry.name.lastIndexOf('/') + 1)
else
entry.name
var dest = File(folder, name)
if (!dest.parentFile!!.exists() && !dest.parentFile!!.mkdirs()) {
dest = SuFile(folder, name)
dest.parentFile!!.mkdirs()
}
SuFileOutputStream(dest).use { out -> zin.copyTo(out) }
}
} catch (e: IOException) {
e.printStackTrace()
throw e
}
}