In this post, I show some of the best practices to read file in Scala. We can use the mkString method to read all the contents of a file into a variable. We can also use the getLines methods to iterator through the contents of a file.
Read all the data into a String
val source = scala.io.Source.fromFile("file.txt")
val lines = try source.mkString finally source.close()
// for file with utf-8 encoding
val lines = scala.io.Source.fromFile("file.txt", "utf-8").getLines.mkString
Scala loop a file
Sometimes we don’t want to load all the contents of a file into the memory, especially if the file is too large. What we want is to loop the file, and process one line each time. See the following example,[Read More...]