Scala: How to open and read text files in Scala

Scala file FAQ: How do I open and read text files in Scala?

When you’re writing Scala scripts, you often want to read text files. Fortunately it’s pretty easy to open and read from text files in Scala. You can just use an approach like this:

import scala.io.Source

val filename = "fileopen.scala"
for (line <- Source.fromFile(filename).getLines()) {
    println(line)
}

This approach uses the scala.io.Source class. Within the for loop I access each line of the file using the line object, and in this case I print each line using println.

A variation of this is to add the mkString method to the file-reading portion of that code, like this:

val fileContents = Source.fromFile(filename).getLines.mkString

That reads the entire contents of the file as a String.

Another nice file-reading example comes from Bruce Eckel's website:

val fileLines = io.Source.fromFile("Colors.scala").getLines.toList
fileLines.foreach(println)

As you can see from that example, you can read an entire text file into a Scala List with what appears to be only one line of source code.

Handling file exceptions

Of course exceptions can be generated when trying to open a file, and if you want to handle your exceptions, you use a syntax similar to the Java try/catch syntax, like this:

import scala.io.Source

val filename = "no-such-file.scala"
try {
  for (line <- Source.fromFile(filename).getLines()) {
    println(line)
  }
} catch {
  case ex: Exception => println("Bummer, an exception happened.")
}

If I change that Exception line to print my exception object, like this:

case ex: Exception => println(ex)

and then run this script again, I can see that this code throws a java.io.FileNotFoundException exception when it fails:

java.io.FileNotFoundException: no-such-file.scala (No such file or directory)

As a result, if I want to catch all the old Java exceptions like I used to, I can write a Scala script like this to catch the Java FileNotFoundException and IOException:

import scala.io.Source
import java.io.{FileReader, FileNotFoundException, IOException}

val filename = "no-such-file.scala"
try {
for (line <- Source.fromFile(filename).getLines()) {
  println(line)
}
} catch {
  case fnfe: FileNotFoundException => println("Couldn't find that file.")
  case ioe:  IOException => println("Had an IOException trying to read that file")
}

In Scala you can also just let your exceptions be thrown. This technique assumes that the calling functions will deal with them.

Opening and reading files in Scala

I know these examples are pretty simple, but when you're first getting started in Scala scripting, little examples like these can be very helpful.

Another thing worth remembering is that you still have access to all the Java file related classes, so you can use a Java FileReader if you prefer, like this:

val reader = new FileReader("foo.txt")

To do this you'll have to import the java.io.FileReader class (and likely other classes), but I just wanted to show that you can take this approach.