Search code examples
filekotlinzipcompression

Create a ZIP file in Kotlin


I'm trying to create a zip file in Kotlin. this is the code:

fun main(args: Array<String>) {
var files: Array<String> = arrayOf("/home/matte/theres_no_place.png", "/home/matte/vladstudio_the_moon_and_the_ocean_1920x1440_signed.jpg")
var out = ZipOutputStream(BufferedOutputStream(FileOutputStream("/home/matte/Desktop/test.zip")))
var data = ByteArray(1024)
for (file in files) {
    var fi = FileInputStream(file)
    var origin = BufferedInputStream(fi)
    var entry = ZipEntry(file.substring(file.lastIndexOf("/")))
    out.putNextEntry(entry)
    origin.buffered(1024).reader().forEachLine {
        out.write(data)
    }
    origin.close()
}
out.close()}

the zip file is created, but the files inside are corrupt!


Solution

  • I'm not sure if you want to do it manually but I found this nice library that works perfectly:

    https://github.com/zeroturnaround/zt-zip

    This library is a nice wrapper of the Java Zip Utils library that include methods for zipping/unzipping both files and directories with a single function.

    For zipping a single file you just need to use the packEntry method:

    ZipUtil.packEntry(File("/tmp/demo.txt"), File("/tmp/demo.zip"))
    

    For the case of zipping a directory and its sub-directories you can use the pack method:

    val dirToCompress = Paths.get("/path/to/my/dir").toFile()
    val targetOutput = Paths.get("/output/path/dir.zip").toFile()
    
    ZipUtil.pack(dirToCompress, targetOutput)
    

    The zip file should have been created in the specified target output.

    You can find more details and examples in the library's documentation.

    Hope this helps =)