相关疑难解决方法(0)

功能尝试和捕获与Scala

是否有更多的自动方式在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)

functional-programming scala

21
推荐指数
3
解决办法
2万
查看次数

Scala最终阻止关闭/刷新资源

有没有更好的方法来确保资源得到正确发布 - 更好的方法来编写以下代码?

        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)

scala

21
推荐指数
2
解决办法
1万
查看次数

Scala中的数据压缩

下面是我尝试实现一个提供压缩/解压缩字符串功能的类:

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那样,关闭GZIPOutputStreamGZIPInputStream丢失的块......我怎么能以"scala"的方式实现它呢?我怎么能改进代码?

scala

4
推荐指数
2
解决办法
6779
查看次数

标签 统计

scala ×3

functional-programming ×1