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

As a quick note, I 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.

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.