loicdescotte
3/25/2013 - 9:27 AM

printToFile function

printToFile 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)
})