loicdescotte
3/25/2013 - 9:23 AM

Scala "print to file" function

Scala "print to file" function

Higher order function to write stuffs in a file, with automatic resources management

Code

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

Usage example

val data = Array("here","is","what","I","want", "to", "print")

printToFile(new File("example.txt"))(p => {
  data.foreach(p.println)
})