Scala 会自动关闭 InputStream 吗? [英] Would scala close the InputStream automatically?
问题描述
我是 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
,但从不调用 reset
和 close代码>
In short - no.
createBufferedSource
creates BufferedSource
with given close
function, but never calls neither for reset
not for close
这篇关于Scala 会自动关闭 InputStream 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!