O'Reilly logo

Scala Cookbook by Alvin Alexander

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

12.2. Writing Text Files

Problem

You want to write plain text to a file, 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()

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.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required