Skip to content

Instantly share code, notes, and snippets.

@marcouberti
Last active September 6, 2024 22:33
Show Gist options
  • Save marcouberti/ab09bb48bbc9772c7ff9edd9042497c3 to your computer and use it in GitHub Desktop.
Save marcouberti/ab09bb48bbc9772c7ff9edd9042497c3 to your computer and use it in GitHub Desktop.
Gzip compression and decompression in Kotlin / Android
import java.io.ByteArrayInputStream
import java.io.ByteArrayOutputStream
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
/**
* Compress a string using GZIP.
*
* @return an UTF-8 encoded byte array.
*/
fun String.gzipCompress(): ByteArray {
val bos = ByteArrayOutputStream()
GZIPOutputStream(bos).bufferedWriter(Charsets.UTF_8).use { it.write(this) }
return bos.toByteArray()
}
/**
* Decompress a byte array using GZIP.
*
* @return an UTF-8 encoded string.
*/
fun ByteArray.gzipDecompress(): String {
val bais = ByteArrayInputStream(this)
lateinit var string: String
GZIPInputStream(bais).bufferedReader(Charsets.UTF_8).use { return it.readText() }
}
@WildFlames
Copy link

if someone needs fewer lines:
fun ByteArray.gzipDecompress(): String = GZIPInputStream(this.inputStream()).bufferedReader(Charsets.UTF_8).use { return it.readText() }

@ruXlab
Copy link

ruXlab commented Feb 13, 2023

@WildFlames .use { return it.readText() } don't do return here as it would cause to return from the ByteArray.gzipDecompress() instead of use

@afollestad
Copy link

afollestad commented Jul 2, 2024

    GZIPInputStream(bais).bufferedReader(Charsets.UTF_8).use { return it.readText() }

…can be…

    return GZIPInputStream(bais).bufferedReader(Charsets.UTF_8).use { it.readText() }

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