3

In the code below, if I uncomment the for loop the file no longer gets deleted

val file = "myfile.csv"
//for (line <- Source.fromFile(file).getLines()) { }
new File(file).delete()

If so is there some type of close function that I should be calling?

deltanovember
  • 42,611
  • 64
  • 162
  • 244
  • 4
    Windows locks files when they're opened, preventing other actions like deletion. You're correct, you do need to explicitly close the file. – Chris Eberle Dec 23 '11 at 04:48

3 Answers3

4

There is some sort of close that you should be calling:

val file = "myfile.csv"
val source = Source.fromFile(file)
for (line <- source.getLines()) { }
source.close
new File(file).delete

but this is a bit tedious. If you rewrite the for loop as

source.getLines().foreach{ line => }

you can then

class CloseAfter[A <: { def close(): Unit }](a: A) {
  def closed[B](f: A => B) = try { f(a) } finally { a.close }
}
implicit def close_things[A <: { def close(): Unit }](a: A) = new CloseAfter(a)

and now your code would become

val file = "myfile.csv"
Source.fromFile(file).closed(_.foreach{ line => })
new File(file).delete

(which would be a benefit if you're doing it many times in your code, or if you already maintain your own library of helpful functions and it would be easy to add the closing implicit just once there so you could use it everywhere).

Rex Kerr
  • 166,841
  • 26
  • 322
  • 407
3

As others have said, yes, you need to close the Source when you're done with it. Another good solution is to use scala-arm to automagically close the file for you.

import resource._

val file = "myfile.csv"
for {
  source <- managed(Source.fromFile(file))
  line <- source.getLines()
} {
}
new File(file).delete
leedm777
  • 23,444
  • 10
  • 58
  • 87
2

After reading "Why doesn't Scala Source close the underlying InputStream?", use instead "scala-incubator / scala-io".

It includes a delete operation on a Path which takes care of everything. That library always always ensures that files are safely closed after each use.

Community
  • 1
  • 1
VonC
  • 1,262,500
  • 529
  • 4,410
  • 5,250