在 Scala 中读取整个文件? [英] Read entire file in Scala?
问题描述
在 Scala 中将整个文件读入内存的简单而规范的方法是什么?(理想情况下,可以控制字符编码.)
What's a simple and canonical way to read an entire file into memory in Scala? (Ideally, with control over character encoding.)
我能想到的最好的是:
scala.io.Source.fromPath("file.txt").getLines.reduceLeft(_+_)
或者我应该使用 Java 的可怕成语之一,其中最好的(不使用外部库)似乎是:
or am I supposed to use one of Java's god-awful idioms, the best of which (without using an external library) seems to be:
import java.util.Scanner
import java.io.File
new Scanner(new File("file.txt")).useDelimiter("\\Z").next()
通过阅读邮件列表讨论,我不清楚 scala.io.Source 甚至应该是规范的 I/O 库.我不明白它的预期目的究竟是什么.
From reading mailing list discussions, it's not clear to me that scala.io.Source is even supposed to be the canonical I/O library. I don't understand what its intended purpose is, exactly.
...我想要一些简单易记的东西.例如,在这些语言中,很难忘记习语......
... I'd like something dead-simple and easy to remember. For example, in these languages it's very hard to forget the idiom ...
Ruby open("file.txt").read
Ruby File.read("file.txt")
Python open("file.txt").read()
推荐答案
val lines = scala.io.Source.fromFile("file.txt").mkString
顺便说一句,scala.
"并不是真正必要的,因为它总是在范围内,当然,您可以完全或部分导入 io 的内容,而不必加上io".
By the way, "scala.
" isn't really necessary, as it's always in scope anyway, and you can, of course, import io's contents, fully or partially, and avoid having to prepend "io." too.
然而,上面的代码使文件保持打开状态.为避免出现问题,您应该像这样关闭它:
The above leaves the file open, however. To avoid problems, you should close it like this:
val source = scala.io.Source.fromFile("file.txt")
val lines = try source.mkString finally source.close()
上面代码的另一个问题是,由于其实现性质,它的速度非常慢.对于较大的文件,应使用:
Another problem with the code above is that it is horrible slow due to its implementation nature. For larger files one should use:
source.getLines mkString "\n"
这篇关于在 Scala 中读取整个文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!