4

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?

Chief
  • 854
  • 12
  • 27
  • 2
    Does this answer your question? [Create file ZIP in Kotlin](https://stackoverflow.com/questions/46222055/create-file-zip-in-kotlin) – Animesh Sahu Jun 09 '20 at 14:51
  • not quite, i actually looked at it before positing my question – Chief Jun 29 '20 at 19:08
  • you have to call `createNewFile()` if the file doesn't exists before appending text. Like `fdir.resolve("sometextfile.txt").takeIf { !it.exists() }?.apply{ createNewFile(); appendText(text) }` – Animesh Sahu Jun 30 '20 at 03:25

1 Answers1

0

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

  • you know i tried this approach, but quite didn't achieve the desired end result. I had issues where the file would open with nothing and some cases it wouldn't. So I combined all solutions and came up with my own. Create two files, Zip (empty) log file (has data). Log file into zip file and export using intent. in summary – Chief Jun 29 '20 at 19:19
  • 1
    Please post your solution so that others can consult in the future – Adonias Alcântara Jun 30 '20 at 20:52