In many examples, it is described that you can use scala.io.Source
to read a whole file like this:
val str = scala.io.Source.fromFile("test.txt").mkString()
But closing the underlying stream is not mentioned.
Why does Scala not provide a convenient way to do that such as with clause in Python? It looks useful but not difficult.
Is there any other better way to do that safely in Scala, I means to read a whole file?
Scala is open to make use of any Java objects and java. io. File is one of the objects which can be used in Scala programming to read and write files. The following is an example program to writing to a file.
Starting Scala 2.13
, the standard library provides a dedicated resource management utility: Using
.
It can be used in this case with scala.io.Source
as it extends AutoCloseable
in order to read from a file and, no matter what, close the file resource afterwards:
import scala.util.Using import scala.io.Source Using(Source.fromFile("file.txt")) { source => source.mkString } // scala.util.Try[String] = Success("hello\nworld\n")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With