2012-06-15 94 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