Skip to content

Instantly share code, notes, and snippets.

@Romain-P
Created August 29, 2023 13:30
Show Gist options
  • Save Romain-P/2caea2c984442642a54fccba9ea151e2 to your computer and use it in GitHub Desktop.
Save Romain-P/2caea2c984442642a54fccba9ea151e2 to your computer and use it in GitHub Desktop.
Create zip in memory.
import java.io.*
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream
fun main() {
val sourcePath = "toZip"
val outputStream = ByteArrayOutputStream()
try {
createZipInMemory(sourcePath, outputStream)
// You can now use the outputStream to access the zipped data
} catch (e: IOException) {
e.printStackTrace()
}
File("test-zip.zip").writeBytes(outputStream.toByteArray())
}
fun createZipInMemory(sourcePath: String, outputStream: ByteArrayOutputStream) {
ZipOutputStream(BufferedOutputStream(outputStream)).use { zipOut ->
val sourceFile = File(sourcePath)
compressFile(sourceFile, sourceFile.name, zipOut)
}
}
fun compressFile(fileToZip: File, fileName: String, zipOut: ZipOutputStream) {
if (fileToZip.isHidden) {
return
}
if (fileToZip.isDirectory) {
val entries = fileToZip.listFiles() ?: return
if (fileName.endsWith("/")) {
zipOut.putNextEntry(ZipEntry(fileName))
zipOut.closeEntry()
} else {
zipOut.putNextEntry(ZipEntry("$fileName/"))
zipOut.closeEntry()
}
for (childFile in entries) {
compressFile(childFile, "$fileName/${childFile.name}", zipOut)
}
return
}
fileToZip.inputStream().use { fis ->
val zipEntry = ZipEntry(fileName)
zipOut.putNextEntry(zipEntry)
val bytes = ByteArray(1024)
var length: Int
while (fis.read(bytes).also { length = it } >= 0) {
zipOut.write(bytes, 0, length)
}
zipOut.closeEntry()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment