Skip to content

Instantly share code, notes, and snippets.

@sgdan
Last active April 4, 2024 06:02
Show Gist options
  • Save sgdan/eaada2f243a48196c5d4e49a277e3880 to your computer and use it in GitHub Desktop.
Save sgdan/eaada2f243a48196c5d4e49a277e3880 to your computer and use it in GitHub Desktop.
Kotlin code to compress/uncompress a string with gzip
import java.io.ByteArrayOutputStream
import java.io.File
import java.nio.charset.StandardCharsets.UTF_8
import java.util.zip.GZIPInputStream
import java.util.zip.GZIPOutputStream
fun gzip(content: String): ByteArray {
val bos = ByteArrayOutputStream()
GZIPOutputStream(bos).bufferedWriter(UTF_8).use { it.write(content) }
return bos.toByteArray()
}
fun ungzip(content: ByteArray): String =
GZIPInputStream(content.inputStream()).bufferedReader(UTF_8).use { it.readText() }
//val content = "a string with some content"
val file = File("gzip.kts")
val content = file.readText()
println("size of original: ${content.length}")
val zipped = gzip(content)
println("size zipped: ${zipped.size}")
val unzipped = ungzip(zipped)
println("size unzipped: ${unzipped.length}")
assert(unzipped == content)
@kirillgroshkov
Copy link

πŸ‘

@dvalvezon
Copy link

πŸ‘ πŸ‘

@asomov
Copy link

asomov commented Sep 17, 2020

Thank you !

@Wikidepia
Copy link

Thank you so much!

@hdformat
Copy link

hdformat commented Jan 1, 2021

you saved me!

@chankang17
Copy link

amen

@mmerdes
Copy link

mmerdes commented Jul 22, 2022

πŸ‘

@iNxmi
Copy link

iNxmi commented Feb 10, 2024

πŸ‘

@satoshihiraishi
Copy link

πŸ‘

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