Scala code to read a text file to an Array (or Seq)

As a quick note about reading files, if you ignore possible exceptions, you can use code like this read a text file into an Array, List, or Seq using Scala:

def readFile(filename: String): Seq[String] = {
    val bufferedSource = io.Source.fromFile(filename)
    val lines = (for (line <- bufferedSource.getLines()) yield line).toList
    bufferedSource.close
    lines
}

The code shown returns a Seq, but you can easily modify it to return an Array if that’s something you want.

As another quick note, if you change the third line to use toSeq rather than toList, like this:

val lines = (for (line <- bufferedSource.getLines()) yield line).toSeq

using the function will generate this error:

java.io.IOException: Stream Closed

I don’t know why that happens at the moment, but I can confirm from simple tests that it does happen.

In summary, if you want to read a text file into an Array, List, or Seq using Scala I hope this is helpful.