Kotlin take a file (.txt, .word, .pdf.....) and zip it to produce fileName.zip with the file inside it

Viewed 692

In kotlin if I have an existing file how do I go about zipping it. For example I create a new File() and I append content to it. Now after appending the content to it. I want to zip this file.

All other solutions I have come across haven't been of help. I am assuming this is straight forward but I am finding trouble how to do this.

val fdir = filesDir
fdir.resolve("sometextfile.txt").takeIf { !it.exists() }?.appendText(text)

val sometextfile = fdir.resolve("sometextfile.txt")
// I now want sometextfile.txt in a zip file called somezipfile.zip

how can I put sometextfile.txt into a zip file called somezipfile.zip so that when it is unzip it contains sometextfile.txt?

1 Answers

A pretty simple approach:

fun zip(inFile: Path, outFile: Path) {
    runCatching {
        val contents = Files.readAllBytes(inFile)
        val out = Files.newOutputStream(outFile, StandardOpenOption.CREATE)

        ZipOutputStream(out).use { zipStream ->
            val zipEntry = ZipEntry(inFile.fileName.toString())
            zipStream.putNextEntry(zipEntry)
            zipStream.write(contents)
        }
    }.onFailure { exception ->
        // exception.printStackTrace()
    }
}

Also be sure to always perform I/O operations outside the UI Thread.

Reference: https://developer.android.com/reference/java/util/zip/ZipOutputStream?hl=en

Related