Skip to content

Instantly share code, notes, and snippets.

@kairos34
Created March 19, 2019 15:06
Show Gist options
  • Save kairos34/75f782b029540e60c2f3b69e5166588e to your computer and use it in GitHub Desktop.
Save kairos34/75f782b029540e60c2f3b69e5166588e to your computer and use it in GitHub Desktop.
Kotlin zip and unzip functions
object ZipManager {
fun zip(files: List<File>, zipFile: File) {
ZipOutputStream(BufferedOutputStream(FileOutputStream(zipFile))).use { output ->
files.forEach { file ->
(file.length() > 1).ifTrue {
FileInputStream(file).use { input ->
BufferedInputStream(input).use { origin ->
val entry = ZipEntry(file.name.toRealName())
output.putNextEntry(entry)
origin.copyTo(output, 1024)
}
}
}
}
}
}
//If we do not set encoding as "ISO-8859-1", European characters will be replaced with '?'.
fun unzip(files: List<File>, zipFile: ZipFile) {
zipFile.use { zip ->
zip.entries().asSequence().forEach { entry ->
zip.getInputStream(entry).use { input ->
BufferedReader(InputStreamReader(input, "ISO-8859-1")).use { reader ->
files.find { it.name.contains(entry.name) }?.run {
BufferedWriter(FileWriter(this)).use { writer ->
var line: String? = null
while ({ line = reader.readLine(); line }() != null) {
writer.append(line).append('\n')
}
writer.flush()
}
}
}
}
}
}
}
}
@irfanirawansukirman
Copy link

hello @kairos34 can you share this function toRealName() ? thank you

@justADeni
Copy link

Ah yes the great pyramids of zip 😆

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment