Just to expand on Daniel's solution, you can shorten things up tremendously by inserting the following import into any file which requires file manipulation:
import scala.io.Source._
With this, you can now do:
val lines = fromFile("file.txt").getLines
I would be wary of reading an entire file into a single String
. It's a very bad habit, one which will bite you sooner and harder than you think. The getLines
method returns a value of type Iterator[String]
. It's effectively a lazy cursor into the file, allowing you to examine just the data you need without risking memory glut.
Oh, and to answer your implied question about Source
: yes, it is the canonical I/O library. Most code ends up using java.io
due to its lower-level interface and better compatibility with existing frameworks, but any code which has a choice should be using Source
, particularly for simple file manipulation.