Scala read file examples

Tags:

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

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, we read the file, only pick up the lines that start with the prefix “xx”, then we transfer it to uppercase, and then print the line. 

Use Java BufferedReader to read file in Scala

Of course, you can also use Java BufferedReader to read file in scala.  See this post on how to read file in Java.