I'm using Scala Source.fromFile however I can't seem to find a nice way of getting it to close the underlying InputStream once the file has been read.
Here's my code that will fail with an AssertionError because the file cannot be deleted.
def main(args : Array[String]) : Unit = {
val myFile = new File("c:/tmp/doodah.txt")
var src = Source.fromFile(myFile)
src.getLines.foreach(l => print(l))
val deleted: Boolean = myFile.delete
assert (deleted , "File was not deleted - maybe the stream hasn't been closed in Source")
}
Source has a method called reset however all that this does is recreate the source from the file.
Internally Source creates an underlying BufferedSource that has a close method. However this is not exposed from Source.
I'd hope that Source would release the file handle once the contents of the file had been read but it doesn't seem to do that.
The best workaround I've seen so far is to essentially cast the Source to a BufferedSource and call close.
try {
src.getLines.foreach(l => print(l))
}
finally src match { case b: scala.io.BufferedSource => b.close }
Alternatively I could create a Source from an InputStream and manage the closing myself.
However this seems somewhat dirty. How are you supposed to release the file handle when using Source?