Jan Vladimir Mostert
Jan Vladimir Mostert

Reputation: 13002

Avoid going to String first when gzipping

Is there a way of doing this gzip without first going to String and then back to ByteArray?

suspend fun gzip(content: ByteArray): ByteArray = withContext(Dispatchers.IO) {
    ByteArrayOutputStream().apply {
        GZIPOutputStream(this).writer(UTF_8).use { it.write(String(content)) }
    }.toByteArray()
}

suspend fun ungzip(content: ByteArray): ByteArray = withContext(Dispatchers.IO) {
    GZIPInputStream(content.inputStream()).bufferedReader(UTF_8).use { it.readText() }.toByteArray()
}

Upvotes: 1

Views: 251

Answers (1)

wartoshika
wartoshika

Reputation: 541

You need to make sure that you close the GZIPOutputStream before consuming it via toByteArray(). When correctly closed the buffer will be written onto the output stream and no truncated data is present.

suspend fun gzip(content: ByteArray): ByteArray = withContext(Dispatchers.IO) {
    ByteArrayOutputStream().apply {
        GZIPOutputStream(this)
           .write(content)
           .close()
    }.toByteArray()
}

You can then consume your data via

suspend fun ungzip(content: ByteArray) = withContext(Dispatchers.IO) {
  GZIPInputStream(zipped.inputStream()).readAllBytes()
}

Upvotes: 1

Related Questions