Scala文件啜泣

Kar*_*lek 20 scala

在这个问题上

在Scala中读取整个文件?

对第一个回答的内容有一个评论

但是我讨厌那些不知道他们可以做"io.File("/ etc/passwd")的人."在行李箱里啜饮.

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

error: object File is not a member of package io
Run Code Online (Sandbox Code Playgroud)

我有scala 2.9.1-1.难道我做错了什么?

dre*_*xin 23

文件不再是stdlib的一部分.相反,你应该使用scala.io.Source.要读取整个文件,您可以执行此操作

val fileContents = io.Source.fromFile("my_file.txt").mkString
Run Code Online (Sandbox Code Playgroud)

但是对于大文件应该避免这种情况.如果使用大文件Source.getLines而是逐行处理文件.Source还有很多其他方便的方法,所以在这里查看http://www.scala-lang.org/api/current/index.html#scala.io.Source