1

I have a list l2 and I want to write the list elements to the file. I'm doing this:

val fw = new FileWriter("src/results.txt", true) ;
for( k <- 1 to l2.length) {
     println(l2(i))
     fw.write(l2(i))
     i+=1
 }
fw.close()

But, it does not write anything. Why is that ?

2
  • are you sure that l2 is not empty? Commented Dec 4, 2014 at 9:07
  • Yes, it's not empty. That's why I did println above fw.write, it's printing everything correctly. It is a list like this List(1,2,3) Commented Dec 4, 2014 at 9:07

2 Answers 2

5

If l2 is List(1,2,3), you are calling .write(int c) of Writer class.

That means 01 02 03 in hex binary is written to file. You can confirm it with hexdump -C src/results.txt

To call .write(String str), try fw.write(l2(i).toString).

See https://docs.oracle.com/javase/7/docs/api/java/io/Writer.html

Sign up to request clarification or add additional context in comments.

Comments

1

To avoid for-loop you can do it like this:

import java.nio.file.Files;
import java.nio.file.Paths
val content = l2.mkString("\n").getBytes
Files.write(Paths.get("src/results.txt"), content)

Comments

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.