By Alvin Alexander. Last updated: November 30, 2017
Here’s some source code for a Scala method that reads a text file that may have comments into a List[String]
:
import scala.io.Source import scala.collection.mutable.ArrayBuffer object FileUtils { /** * Get the contents of a text file while skipping over comment lines and * blank lines. This is useful when reading a data file that can have lines * beginning with '#', or blank lines, such as a file that looks like this: * ------------------- * foo * # this is a comment * * bar * ------------------- */ def getFileContentsWithoutCommentLines(filename: String): List[String] = { (for (line <- Source.fromFile(filename).getLines if !line.trim.matches("") if !line.trim.matches("#.*")) yield line ).toList } }
Be careful with this method, because it may leave the file handle open for the length of time the JVM is running. I explain this problem and the solution in my How to read text files in Scala tutorial. Because of that problem, this method is mostly suited for short-running applications, like little shell scripts.