This is an excerpt from the 1st Edition of 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.
Note that a better solution is shown below that uses the scala.util.Using
control structure.
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 IOException
s, 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:
import java.io._ /** * write a `Seq[String]` to the `filename`. * note: does not handle exceptions. */ 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`. * note: does not handle exceptions. */ 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.
Update: Writing to a file with scala.util.Using
As a brief update, if you want to write to a file using Scala and scala.util.Using
, I believe this function is correct:
def writeFile(filename: String, content: String): Try[Unit] = Using(BufferedWriter(FileWriter( File(filename), false))) { bufferedWriter => bufferedWriter.write(content) }
In a related note, you can also read from a file using scala.util.Using
like this:
def readFile(filename: String): Try[String] = Using(BufferedReader(FileReader(filename))) { reader => val rez = Iterator.continually(reader.readLine()).takeWhile(_ != null) rez.mkString("\n") }
If you ever wanted to use scala.util.Using
to write to a file or read from a file, I hope this is helpful.
See Also
- The Java
FileWriter
class - The Java
PrintWriter
class - The coderanch.com
PrintWriter
versusFileWriter
page
this post is sponsored by my books: | |||
#1 New Release |
FP Best Seller |
Learn Scala 3 |
Learn FP Fast |