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.”


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.


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

// PrintWriter
val pw = new PrintWriter(new File("hello.txt" ))
pw.write("Hello, world")

// FileWriter
val file = new File(canonicalFilename)
val bw = new BufferedWriter(new FileWriter(file))


Although I normally use a FileWriter to write plain text to a file, a good post at 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.

See Also

The Scala Cookbook

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

You can find the Scala Cookbook at these locations:


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

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.