Scala 会自动关闭 InputStream 吗? [英] Would scala close the InputStream automatically?

查看:87
本文介绍了Scala 会自动关闭 InputStream 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Scala 的新手,对流关闭机制不熟悉.我写了一些这样的代码.

I'm a newbie of scala and not familiar to the stream close mechanism. I wrote some code like this.

def loadResourceAsString(path: String) = {

  val is = this.getClass().getResourceAsStream(path)

  Source.fromInputStream(is).getLines().mkString("\n")

}

我在 Scala 源代码中发现了这个.Source 将返回一个 BufferedSource,它覆盖关闭方法以关闭输入流.

I found this in scala source code. The Source would return a BufferedSource which override close method to close the input stream.

def fromInputStream(is: InputStream)(implicit codec: Codec): BufferedSource =
  createBufferedSource(is, reset = () => fromInputStream(is)(codec), close = () => is.close())(codec)

如果有异常,scala会不会通过自己的机制执行close方法?

If there was exception, would scala execute the close method by its own mechanism?

或者,我应该像 java 一样在 finally 块中明确关闭输入流吗?

Or, should I close input stream in finally block explicitly just like java?

推荐答案

简而言之 - 没有.createBufferedSource 使用给定的 close 函数创建 BufferedSource,但从不调用 resetclose

In short - no. createBufferedSource creates BufferedSource with given close function, but never calls neither for reset not for close

这篇关于Scala 会自动关闭 InputStream 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆