Search code examples
bashkotlinunzip

Unzip a file in kotlin script [.kts]


I was toying with the idea of rewriting some existing bash scripts in kotlin script.

One of the scripts has a section that unzips all the files in a directory. In bash:

unzip *.zip

Is there a nice way to unzip a file(s) in kotlin script?


Solution

  • The easiest way is to just use exec unzip (assuming that the name of your zip file is stored in zipFileName variable):

    ProcessBuilder()
        .command("unzip", zipFileName)
        .redirectError(ProcessBuilder.Redirect.INHERIT)
        .redirectOutput(ProcessBuilder.Redirect.INHERIT)
        .start()
        .waitFor()
    

    The different approach, that is more portable (it will run on any OS and does not require unzip executable to be present), but somewhat less feature-full (it will not restore Unix permissions), is to do unzipping in code:

    import java.io.File
    import java.util.zip.ZipFile
    
    ZipFile(zipFileName).use { zip ->
        zip.entries().asSequence().forEach { entry ->
            zip.getInputStream(entry).use { input ->
                File(entry.name).outputStream().use { output ->
                    input.copyTo(output)
                }
            }
        }
    }
    

    If you need to scan all *.zip file, then you can do it like this:

    File(".").list { _, name -> name.endsWith(".zip") }?.forEach { zipFileName ->
        // any of the above approaches        
    }
    

    or like this:

    import java.nio.file.*
    
    Files.newDirectoryStream(Paths.get("."), "*.zip").forEach { path ->
        val zipFileName = path.toString()
        // any of the above approaches        
    }