Scala 中的数据压缩 [英] Data compression in Scala
问题描述
下面是我尝试实现一个提供压缩/解压缩字符串功能的类:
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)
}
}
}
如您所见,关闭 GZIPOutputStream
和 GZIPInputStream
的 finally
块丢失了......我怎么能在''scala' 方式?我该如何改进代码?
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?
推荐答案
由于您使用的是老式"try
语句并将其显式转换为 scala.util.Try
,真的没有理由不在你的 try
之后添加一个 finally
块.
Since you're using the "old fashioned" try
statement and explicitly turning it into a scala.util.Try
, there really is no reason not to add a finally
block after your try
.
不过,在这种特定情况下,关闭没有什么意义,例如,您的 ByteArrayInputStream
- 它不是真正的开放资源,不需要关闭.在这种情况下,您可以通过这种方式简化代码并使其更加地道:
In this specific case though, there is little point in closing, for example, your ByteArrayInputStream
- it's not really an open resource and does not need to be closed. In which case you can simplify your code and make it much more idiomatic this way:
def inflate(deflatedTxt: String): Try[String] = Try {
val bytes = Base64.decodedBase64(deflatedTxt)
val zipInputStream = GZIPInputStream(new ByteArrayInputStream(bytes))
IOUtils.toString(zipInputStream)
}
我个人不会声明 bytes
和 zipInputStream
因为它们只使用一次,但这是一个偏好问题.
I personally would not declare bytes
and zipInputStream
since they're only used once, but that's a matter of preference.
这里的技巧是使用 finally
块调用 scala.util.Try.apply
- 我不确定不通过调用map
实际上并没有修改任何东西,这对我来说似乎有点疏忽.我期待在 scala.util.Try
中看到 andThen
或 eventually
方法,但它似乎不存在(还没有?).
The trick here is having a finally
block with a call to scala.util.Try.apply
- I'm not sure that's possible without going through a call to map
that doesn't actually modify anything, which seems like a bit of an oversight to me. I was expecting to see an andThen
or eventually
method in scala.util.Try
, but it doesn't seem to be there (yet?).
这篇关于Scala 中的数据压缩的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!