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 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()
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
FileWriter. For instance, while both classes extend from
Writer, and both can be used for writing plain text to files,
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.
- My Java file utilities, and my Scala file utilities
- The Java
- The Java
- The coderanch.com
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.