Created
March 19, 2019 15:06
-
-
Save kairos34/75f782b029540e60c2f3b69e5166588e to your computer and use it in GitHub Desktop.
Kotlin zip and unzip functions
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
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() | |
} | |
} | |
} | |
} | |
} | |
} | |
} | |
} |
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
hello @kairos34 can you share this function toRealName() ? thank you