Read entire file in Scala?

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.


val lines = scala.io.Source.fromFile("file.txt").mkString

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 horribly slow due to its implementation. For larger files one should use:

source.getLines mkString "\n"

Tags:

Scala