A Scala method to write a list of strings to a file

As a brief note today, here’s a Scala method that writes the strings in a list — more accurately, a Seq[String] — to a file:

def writeFile(filename: String, lines: Seq[String]): Unit = {
    val file = new File(filename)
    val bw = new BufferedWriter(new FileWriter(file))
    for (line <- lines) {
        bw.write(line)
    }
    bw.close()
}

One important thing to note is that this method assumes that the strings are formatted however you want them to be formatted. For example, it assumes that each string has a newline character at the end of it. If you don’t have a newline character at the end of each string, you’ll end up with one long line of text in the output file.

It’s also worth mentioning that this method can throw exceptions if the file-writing process fails for some reason, such as if you don’t have permission to write to the file.