Created
October 7, 2024 09:06
-
-
Save johnkil/59a2e42f2d6b6136762cb32278520c5e to your computer and use it in GitHub Desktop.
This file contains 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.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