使用 scala.io.Source 的正确方法是什么?
在许多示例中,描述了您可以使用 scala.io.Source 来读取整个文件,如下所示:
val str = scala.io.Source.fromFile("test.txt").mkString()
但没有提到关闭底层流。
为什么 Scala 没有提供像 Python 中的 with 子句那样方便的方法来做到这一点?看起来很有用,但并不难。
有没有其他更好的方法可以在 Scala 中安全地做到这一点,我的意思是读取整个文件?
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.
Why does Scala not provide a convenient way to do that such as with clause in Python? It looks useful but not difficult.
Is there any other better way to do that safely in Scala, I means to read a whole file?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
从 Scala 2.13 开始,标准库提供了专用的资源管理实用程序:
使用
。在这种情况下,它可以与 < 一起使用code>scala.io.Source 因为它扩展了
AutoCloseable
以便从文件中读取数据,然后无论如何,关闭文件资源:Starting
Scala 2.13
, the standard library provides a dedicated resource management utility:Using
.It can be used in this case with
scala.io.Source
as it extendsAutoCloseable
in order to read from a file and, no matter what, close the file resource afterwards:为了完整性,
应该把事情做好。
For the sake of completeness
Should get things done.
Scala 的 io 库只是为了为有限的需求提供支持而进行了修改。我们努力为 Scala 提供一个经过深思熟虑的 io 库,目前托管在 assembla,还有一个 github 存储库。
如果您打算使用 I/O 除了读取短期进程上的临时文件之外,您最好使用 Java 库,或者查看编译器中当前可用的 I/O 支持(这将需要 scala) -compiler.jar 随应用程序一起分发)。
自 Scala 2.13 起,标准库 (
scala.util.Using
) 中提供了自动资源管理。对于较旧的 Scala 版本,请查看此问题,或查看这个库(该库在该问题的已接受答案中有所体现)。因此,在 Scala 2.13 或更高版本上,这可以正常工作:
Scala's
io
library was just hack done to provide support for limited needs. There was an effort to provide a well-thought io library to Scala, which is currently hosted at assembla, with a github repository as well.If you are going to use I/O for anything more than reading the occasional file on short-lived processes, you'd better either use Java libraries, or look at the I/O support presently available in the compiler (which will require scala-compiler.jar to be distributed with the app).
Automatic resource management is provided since Scala 2.13 in the standard library (
scala.util.Using
). For older Scala versions look at this question, or at this library (which is featured in the accepted answer at that question).So, on Scala 2.13 or newer, this works correctly:
我建议使用using,这会让你的代码更整洁、更可靠
Scala 2.13 在库中添加了
Using
。因此,附带条件是Using.apply
返回Try
,在 Scala 2.13 上它变成:I recommend using the using, which makes your code neater and more reliable
Scala 2.13 added
Using
to the library. So, with the proviso thatUsing.apply
returns aTry
, on Scala 2.13 it becomes: