2012-06-15 91 views
17

在这个问题上斯卡拉文件啜食

Read entire file in Scala?

存在于读取

第一个答案评论,但我讨厌的人不知道他们能做到“IO。在trunk中的文件(“/ etc/passwd”).slurp“。

当我尝试这样做,斯卡拉告诉我

error: object File is not a member of package io 

我有斯卡拉2.9.1-1。难道我做错了什么?

+1

[阅读](http://stackoverflow.com/a/1330808/571189)这里... –

回答

20

文件不再是stdlib的一部分。相反,你应该使用scala.io.Source。要阅读整个文件,你可以做

val fileContents = io.Source.fromFile("my_file.txt").mkString 

这应该避免大文件虽然。如果大文件使用Source.getLines,请逐行处理文件。 Source也有很多其他方便的方法,所以在这里检查它们http://www.scala-lang.org/api/current/index.html#scala.io.Source