Skip to content

Instantly share code, notes, and snippets.

@johnkil
Created October 7, 2024 09:06
Show Gist options
  • Save johnkil/59a2e42f2d6b6136762cb32278520c5e to your computer and use it in GitHub Desktop.
Save johnkil/59a2e42f2d6b6136762cb32278520c5e to your computer and use it in GitHub Desktop.
import java.nio.file.*
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
import kotlin.io.path.*
@OptIn(ExperimentalPathApi::class)
fun ZipOutputStream.addFolder(entryName: String, folder: Path) {
for (path in folder.walk()) {
val relativized = folder.relativize(path)
val prefix = if (entryName.isNotEmpty()) {
"$entryName/"
} else ""
addEntry(prefix + relativized.joinToString(separator = "/") { it.name }) {
path.inputStream().use {
it.copyTo(this)
}
}
}
}
fun ZipOutputStream.addFile(entryName: String, byteArray: ByteArray) {
addEntry(entryName) { write(byteArray) }
}
fun ZipOutputStream.addEntry(entryName: String, operation: () -> Unit) {
val zipEntry = ZipEntry(entryName)
try {
putNextEntry(zipEntry)
operation()
}
catch (ex: Exception) {
fileLogger().error("Failed to add file to stream", ex)
}
finally {
closeEntry()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment