5

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?

1
  • "had no luck, what an I doing wrong" Perhaps if you told us what was not working, rather than "won't work" and "no luck" we might be able to help Commented Jul 23, 2016 at 16:09

2 Answers 2

4

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()
Sign up to request clarification or add additional context in comments.

Comments

0

writer needs to flush to the disk, and then be closed.

writer.flush
writer.close

Or you can try another way: using PrintWriter

1 Comment

"does not pass the build " and how were we supposed to know that? Telepathy? Please add the error messages to your question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.