Scala finally block closing/flushing resource

后端 未结 3 660
清歌不尽
清歌不尽 2020-12-09 03:23

Is there a better way to ensure resources are properly released - a better way to write the following code ?

        val out: Option[FileOutputStream] = try         


        
3条回答
  •  臣服心动
    2020-12-09 04:14

    Alternatively you can do this with Choppy's Lazy TryClose monad.

    val output = for {
      fin   <- TryClose(in)
      fout  <- TryClose.wrapWithCloser(new FileOutputStream(path))(out => {out.flush(); out.close();})
    } yield wrap(Iterator.continually(fin.read).takeWhile(-1 != _).foreach(fout.get.write))
    
    // Then execute it like this:
    output.resolve
    

    More info here: https://github.com/choppythelumberjack/tryclose

    (just be sure to import tryclose._ and tryclose.JavaImplicits._)

提交回复
热议问题