API to write a collection to a file


I found that it is possible to use Source.fromFile(“hello.txt”).readLines() to read a file in Scala but I am not able to find a similar API to write a collection to a file.


There are certainly a lot of ways to do it. Saving out a json file for instance. If you want just a csv file maybe take a look at the Kantan library: https://nrinaudo.github.io/kantan.csv/tut/serialising_collections.html



I’d probably use Java NIO. Running this code in the Scala REPL…

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

val lines = "Line 1" :: "Line 2" :: Nil
val file = Paths.get("lines.txt")
Files.write(file, lines.asJava, StandardCharsets.UTF_8)

…produces lines.txt:

Line 1
Line 2



I’d recommend using better-files, which will hopefully be part of the upcoming Scala Platform:

import better.files._
File("hello.txt").appendLines(List("Hello", "World"))

and to read a file:

val lines = File("hello.txt").lines