Scala - How to open and read files in Scala

Scala file FAQ: How do I open and read 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 a file 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)
}

As you can see, this approach uses the scala.io.Source class. Within the for loop I can now access each line of the file using the 'line' object, and in this case I'm printing each line using println.

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

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

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 you can generate exceptions 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 ex: FileNotFoundException => println("Couldn't find that file.")
  case ex: IOException => println("Had an IOException trying to read that file")
}

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.

Share it!

There’s just one person behind this website; if this article was helpful (or interesting), I’d appreciate it if you’d share it. Thanks, Al.

Add new comment

The content of this field is kept private and will not be shown publicly.

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.
By submitting this form, you accept the Mollom privacy policy.