Scala: write string to file in one statement

It is strange that no one had suggested NIO.2 operations (available since Java 7):

import java.nio.file.{Paths, Files}
import java.nio.charset.StandardCharsets

Files.write(Paths.get("file.txt"), "file contents".getBytes(StandardCharsets.UTF_8))

I think this is by far the simplest and easiest and most idiomatic way, and it does not need any dependencies sans Java itself.

Leave a Comment