Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scala- writing list to file using foreach

Tags:

scala

I'm trying to write a list I have into a file and I'm trying to it with the foreach call, as can be done with println. this works:

list.foreach(println)

but this won't work:

val file = "whatever.txt"
val writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)))
list.foreach(writer.write)

I've tried some other ways to print to a file and in all of them had no luck, what an I doing wrong?

like image 400
boaz Avatar asked Oct 18 '22 05:10

boaz


1 Answers

Here's a complete example that compiles and runs. Your code was missing close() so everything your wrote in BufferedWriter remained in the buffer and never reached the disk.

import java.io._

val file = "whatever.txt"
val writer = new BufferedWriter(new FileWriter(file))
List("this\n","that\n","other\n").foreach(writer.write)
writer.close()
like image 92
jwvh Avatar answered Oct 21 '22 02:10

jwvh