Last active
September 6, 2024 22:33
-
-
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() } | |
} |
@WildFlames .use { return it.readText() }
don't do return here as it would cause to return from the ByteArray.gzipDecompress()
instead of use
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
if someone needs fewer lines:
fun ByteArray.gzipDecompress(): String = GZIPInputStream(this.inputStream()).bufferedReader(Charsets.UTF_8).use { return it.readText() }