Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 990
Valentin Tihomirov Avatar asked Nov 29 '22 10:11

Valentin Tihomirov


1 Answers

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()
like image 108
Łukasz Avatar answered Dec 05 '22 14:12

Łukasz