使用 scala.io.Source 的正确方法是什么? [英] What's the right way to use scala.io.Source?

查看:66
本文介绍了使用 scala.io.Source 的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在很多例子中,都描述了你可以使用 scala.io.Source 像这样读取整个文件:

In many examples, it is described that you can use scala.io.Source to read a whole file like this:

val str = scala.io.Source.fromFile("test.txt").mkString()

但是没有提到关闭底层流.

But closing the underlying stream is not mentioned.

为什么 Scala 没有提供一种方便的方法来做到这一点,例如 Python 中的 with 子句?看起来有用但并不难.

Why does Scala not provide a convenient way to do that such as with clause in Python? It looks useful but not difficult.

在 Scala 中有没有其他更好的方法可以安全地做到这一点,我的意思是读取整个文件?

Is there any other better way to do that safely in Scala, I means to read a whole file?

推荐答案

为了完整性

val testTxtSource = scala.io.Source.fromFile("test.txt")
val str = testTxtSource.mkString()
testTxtSource.close()

应该把事情做好.

这篇关于使用 scala.io.Source 的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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