How do I append to a file in Scala?

There is no scala-specific IO implementation at the moment, although I understand one written by Jesse Eichar is in incubation. I'm not sure, to what extent this makes use of the new File (path) API in JDK7. Because of this, for now I would go with the simple Java:

val fw = new FileWriter("test.txt", true)
try {
  fw.write( /* your stuff */)
}
finally fw.close() 

val fw = new FileWriter("test.txt", true) ; 
fw.write("This line appended to file!") ; 
fw.close()

There is a cleaner way — without using external dependencies:

import scala.tools.nsc.io.File

File("filename").writeAll("hello!") // or appendAll("hello!")

or

import scala.tools.nsc.io.Path

Path("/path/to/file").createFile().appendAll("hello!")

Update (November 2020) These APIs are stable (unlike claims in the comments). They have been around since my original answer in 2015 and they are still present in the latest release.

Tags:

Scala