Last active
June 21, 2023 05:30
-
-
Save owainlewis/1e7d1e68a6818ee4d50e to your computer and use it in GitHub Desktop.
Gzip Scala
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.{ByteArrayOutputStream, ByteArrayInputStream} | |
import java.util.zip.{GZIPOutputStream, GZIPInputStream} | |
import scala.util.Try | |
object Gzip { | |
def compress(input: Array[Byte]): Array[Byte] = { | |
val bos = new ByteArrayOutputStream(input.length) | |
val gzip = new GZIPOutputStream(bos) | |
gzip.write(input) | |
gzip.close() | |
val compressed = bos.toByteArray | |
bos.close() | |
compressed | |
} | |
def decompress(compressed: Array[Byte]): Option[String] = | |
Try { | |
val inputStream = new GZIPInputStream(new ByteArrayInputStream(compressed)) | |
scala.io.Source.fromInputStream(inputStream).mkString | |
}.toOption | |
} |
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
class GzipSpec extends WordSpecLike with Matchers { | |
"The GZIP object" should { | |
"decompress a compressed string" in { | |
val input = Gzip.compress("Hello World".getBytes("UTF-8")) | |
Gzip.decompress(input) shouldBe Some("Hello World") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks. Extra example of sequential generating of gziped CSV files with os-lib:
Add the following to
build.sbt
then