How to write to a file in Scala?

yura picture yura · Jan 5, 2011 · Viewed 149.6k times · Source

For reading, there is the useful abstraction Source. How can I write lines to a text file?

Answer

Rex Kerr picture Rex Kerr · Jan 5, 2011

This is one of the features missing from standard Scala that I have found so useful that I add it to my personal library. (You probably should have a personal library, too.) The code goes like so:

def printToFile(f: java.io.File)(op: java.io.PrintWriter => Unit) {
  val p = new java.io.PrintWriter(f)
  try { op(p) } finally { p.close() }
}

and it's used like this:

import java.io._
val data = Array("Five","strings","in","a","file!")
printToFile(new File("example.txt")) { p =>
  data.foreach(p.println)
}