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

By Alvin Alexander. Last updated: August 9, 2022

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.

alvinalexander.com
is owned and operated by
Valley Programming, LLC

In regards to links to Amazon.com, As an Amazon Associate
I (Valley Programming, LLC) earn from qualifying purchases

This website uses cookies: learn more

AltStyle によって変換されたページ (->オリジナル) /