How to read a file line by line and close it afterwards in Scala?
Asked Answered
O

1

7

Normally, they will tell you to

import scala.io.Source
for(line <- Source.fromPath("myfile.txt").getLines())
  println(line)

which seems to leave the file open. What is a closeable counterpart?

Opinionated answered 28/11, 2015 at 14:18 Comment(0)
M
25

You can close the Source and this will close your file.

import scala.io.Source

val source = Source.fromFile("myfile.txt")
for (line <- source.getLines())
   println(line)
source.close()
Melone answered 28/11, 2015 at 14:35 Comment(3)
Thanks, this answer distracted me. I keep wondering, why do you all guys use fromPath instead of fromFile? My compiler says that fromPath is not a member of Source and I must use fromFile instead.Opinionated
You could also draw attention to the using approachOpinionated
"why do you all guys use fromPath instead of fromFile?" You are one of those guys. Tbh I just copied this from your question. Actually there is no such method. I fixed my answer to use fromFile.Tacmahack

© 2022 - 2024 — McMap. All rights reserved.