Create file ZIP in Kotlin

If you use Kotlin's IOStreams.copyTo() extension, it will do the copying work for you, and that ended up working for me.

So replace this:

origin.buffered(1024).reader().forEachLine {
    out.write(data)
}

With this:

origin.copyTo(out, 1024)

I also had issues with the ZipEntry having a leading slash, but that could just be because I'm on Windows.

Note: I didn't end up needing to call closeEntry() to get this to work but it is recommended.


I did a mix:

fun main(args: Array<String>) {
    val files: Array<String> = arrayOf("/home/matte/theres_no_place.png", "/home/matte/vladstudio_the_moon_and_the_ocean_1920x1440_signed.jpg")
    ZipOutputStream(BufferedOutputStream(FileOutputStream("/home/matte/Desktop/test.zip"))).use { out ->
        for (file in files) {
            FileInputStream(file).use { fi ->
                BufferedInputStream(fi).use { origin ->
                    val entry = ZipEntry(file.substring(file.lastIndexOf("/")))
                    out.putNextEntry(entry)
                    origin.copyTo(out, 1024)
                }
            }
        }
    }
}

It works perfectly!

Tags:

Zip

Kotlin