是否有更多的自动方式在Scala中打开资源并将方法应用于此方法(直接从java转换),使用__CODE__但也包括finally等.
var is: FileInputStream = null
try {
is = new FileInputStream(in)
func(is)
} catch {
case e: IOException =>
println("Error: could not open file.")
println(" -> " + e)
exit(1)
} finally {
if(is) is.close()
}
Run Code Online (Sandbox Code Playgroud) 有没有更好的方法来确保资源得到正确发布 - 更好的方法来编写以下代码?
val out: Option[FileOutputStream] = try {
Option(new FileOutputStream(path))
} catch {
case _ => None
}
if (out.isDefined) {
try {
Iterator.continually(in.read).takeWhile(-1 != _).foreach(out.get.write)
} catch {
case e => println(e.getMessage)
} finally {
in.close
out.get.flush()
out.get.close()
}
}
Run Code Online (Sandbox Code Playgroud) 下面是我尝试实现一个提供压缩/解压缩字符串功能的类:
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)
}
}
}
Run Code Online (Sandbox Code Playgroud)
正如你所看到的finally那样,关闭GZIPOutputStream和GZIPInputStream丢失的块......我怎么能以"scala"的方式实现它呢?我怎么能改进代码?