How to write text files in Scala

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is Recipe 12.2, “How to write text files in Scala.”

Problem

You want to write plain text to a file in Scala, such as a simple configuration file, text data file, or other plain-text document.

Solution

Scala doesn’t offer any special file writing capability, so fall back and use the Java PrintWriter or FileWriter approaches:

// PrintWriter
import java.io._
val pw = new PrintWriter(new File("hello.txt" ))
pw.write("Hello, world")
pw.close

// FileWriter
val file = new File(canonicalFilename)
val bw = new BufferedWriter(new FileWriter(file))
bw.write(text)
bw.close()

Note that you’ll generally want to add a newline character (\n) to each line you print with these approaches. (If you don’t, you’ll get one long line of output.)

Discussion

Although I normally use a FileWriter to write plain text to a file, a good post at coderanch.com describes some of the differences between PrintWriter and FileWriter. For instance, while both classes extend from Writer, and both can be used for writing plain text to files, FileWriter throws IOExceptions, whereas PrintWriter does not throw exceptions, and instead sets Boolean flags that can be checked. There are a few other differences between the classes; check their Javadoc for more information.

Update: See the Comments section below for a note about explicitly declaring the charset when using PrintWriter. Note that PrintWriter constructors let you specify the charset, but FileWriter does not. The Java 8 FileWriter Javadoc suggests that you use an OutputStreamWriter on a FileOutputStream to specify the file encoding.

Example Scala file-writing methods

As an example of how to use these file-writing methods, here are two writeFile methods from my little Scala file utilities project:

/**
 * write a `Seq[String]` to the `filename`.
 */
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()
}

/**
 * write a `String` to the `filename`.
 */
def writeFile(filename: String, s: String): Unit = {
    val file = new File(filename)
    val bw = new BufferedWriter(new FileWriter(file))
    bw.write(s)
    bw.close()
}

Note that those methods don’t handle exceptions, but you can use them as the start of your own methods, if you’d like.

See Also

The Scala Cookbook

This tutorial is sponsored by the Scala Cookbook, which I wrote for O’Reilly:

Comments

Permalink

Wow, strangely hard to find good simple info on this, thanks! But wouldn't it be better to specify the output encoding? ex:
val pw = new PrintWriter(new File("hello.txt"), "UTF-8")

Sure, I have no problem with explicitly declaring the charset. I know that PrintWriter uses the “default charset for this instance of the JVM,” but it is probably more clear to declare “I want UTF-8” or “I want UTF-16,” rather than leaving that up to the JVM implementation.

Thanks for the comment, that’s a good point.

Add new comment

Anonymous format

  • Allowed HTML tags: <em> <strong> <cite> <code> <ul type> <ol start type> <li> <pre>
  • Lines and paragraphs break automatically.