Scala data compression

The following 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 blocks finallythat close GZIPOutputStreamand GZIPInputStreamare missing ... how could I implement this in `` w60> ''? How can I improve the code?

+4
source share
3 answers

Since you use the "old-fashioned" instruction tryand explicitly turn it into scala.util.Try, there really is no reason not to add a block finallyafter try.

, , , ByteArrayInputStream - . :

def inflate(deflatedTxt: String): Try[String] = Try {
   val bytes = Base64.decodedBase64(deflatedTxt)
   val zipInputStream = GZIPInputStream(new ByteArrayInputStream(bytes))
   IOUtils.toString(zipInputStream)
}

bytes zipInputStream, , .

finally scala.util.Try.apply - , , map, , . andThen eventually scala.util.Try, , , (?).

+7

, ( close() GZIP):

def deflate(txt: String): Try[String] = Try {
    val arrOutputStream = new ByteArrayOutputStream()
    val zipOutputStream = new GZIPOutputStream(arrOutputStream)
    zipOutputStream.write(txt.getBytes)
    zipOutputStream.close()
    Base64.encodeBase64String(arrOutputStream.toByteArray)
}
+4

All Articles