Skip to content

Instantly share code, notes, and snippets.

@eren
Created April 4, 2019 10:53
Show Gist options
  • Select an option

  • Save eren/2924b47db28fa18d021777151751176f to your computer and use it in GitHub Desktop.

Select an option

Save eren/2924b47db28fa18d021777151751176f to your computer and use it in GitHub Desktop.
Zlib Inflate/Decompress in Kotlin
/**
* Zlib decompress a file and return its contents
*
* @param filePath absolute path to file
* @return unzipped file contents
*/
fun decompress(filePath: String) : String {
val content = File(filePath).readBytes()
val inflater = Inflater()
val outputStream = ByteArrayOutputStream()
val buffer = ByteArray(1024)
inflater.setInput(content)
while (!inflater.finished()) {
val count = inflater.inflate(buffer)
outputStream.write(buffer, 0, count)
}
outputStream.close()
return outputStream.toString(UTF_8)
}
@dschrul
Copy link

dschrul commented Jun 10, 2020

This helped, thank you!

@marcouberti
Copy link

In my case inflater.finished() is never true so I do:

/**
 * Decompress a byte array using ZLIB.
 *
 * @return an UTF-8 encoded string.
 */
fun ByteArray.zlib(): String {
    val inflater = Inflater()
    val outputStream = ByteArrayOutputStream()

    return outputStream.use {
        val buffer = ByteArray(1024)

        inflater.setInput(this)

        var count = -1
        while (count != 0) {
            count = inflater.inflate(buffer)
            outputStream.write(buffer, 0, count)
        }

        inflater.end()
        outputStream.toString("UTF-8")
    }
}

@jmkolbe
Copy link

jmkolbe commented Oct 20, 2021

On the Android platform at least, there's InflaterInputStream, allowing for nifty things like InflaterInputStream(inputBytes.inputStream()).bufferedReader().use { it.readText() }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment