Last active
June 3, 2025 06:14
-
-
Save marcouberti/ab09bb48bbc9772c7ff9edd9042497c3 to your computer and use it in GitHub Desktop.
Gzip compression and decompression in Kotlin / Android
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
…can be…