As a quick Scala/Java tip, to append to a file when writing to a text file in a Scala or Java application, create your FileWriter with the append flag set to true
, like this:
val bw = new BufferedWriter(new FileWriter(new File("/tmp/file.out"), true)) // <-- 'true'
bw.write("Hello, world\n")
bw.close
FileWriter
takes two arguments, so that code might be easier to read when it’s formatted like this:
val bw = new BufferedWriter(
new FileWriter(
new File("/tmp/file.out"),
true
)
)
bw.write("Hello, world\n")
bw.close
Note: Appending to a text file with Scala 3
As a quick update, a great thing about Scala 3 is that you can get rid of all those new
keywords, so the first part of that last example looks like this in Scala 3:
val bw = BufferedWriter(
FileWriter(
File("/tmp/file.out"),
true
)
)