Scala: Read a text file that has comment tags

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.

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.
By submitting this form, you accept the Mollom privacy policy.