Data compression in Scala

Viewed 9897

Here below is my attempt to implement a class that provides functionality for compressing/decompressing strings:

object GZipHelper {

  def deflate(txt: String): Try[String] = {
    try {
      val arrOutputStream = new ByteArrayOutputStream()
      val zipOutputStream = new GZIPOutputStream(arrOutputStream)
      zipOutputStream.write(txt.getBytes)
      new Success(Base64.encodeBase64String(arrOutputStream.toByteArray))
    } catch {
      case _: e => new Failure(e)
    }
  }

  def inflate(deflatedTxt: String): Try[String] = {
    try {
      val bytes = Base64.decodedBase64(deflatedTxt)
      val zipInputStream = GZIPInputStream(new ByteArrayInputStream(bytes))
      new success(IOUtils.toString(zipInputStream))
    } catch {
      case _: e => new Failure(e)
    }
  }
}

As you can see, the finally blocks that close GZIPOutputStream and GZIPInputStream are missing... how could I implement this in the ''scala'' way? How could I improve the code?

4 Answers

You can use scala-compress https://github.com/gekomad/scala-compress

compress string:

val aString: String = "foo"
val compressed: Try[Array[Byte]] = zipString(aString, charSetName = "UTF-8") 

decompress:

val compressedArray: Array[Byte] = ???
val decompressed: Try[Array[Byte]] = unzipString(compressedArray)  
new String(decompressed, "UTF-8")
Related