Calling methods such as mkString
directly over scala.io.Source
methods such as fromFile
leaks the underneath file handle. To mitigate this, one way is to manually call the close
method to free/close these resources yourself. However, the ideal and right approach is to use Scala's automatic resource management. scala.util.Using
helps automatically manage either a single resource or multiple resources, thus preventing any underneath file handles from leaking.
val fileContents = Source.fromFile("file.txt").mkString
// Manually closing the file yourself
val fileSource = Source.fromFile("file.txt")
val fileContents = fileSource.mkString
fileSource.close()
// Using the automatic resource management
Using(Source.fromFile("file.txt")) { reader =>
val fileContents = reader.mkString
// process the `fileContents`
}
// Handling multiple resources
Using.Manager { manage =>
val fooReader = manage(new BufferedReader(new FileReader("foo.txt")))
val barReader = manage(new BufferedReader(new FileReader("bar.txt")))
// ...
}