问题
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?
回答1:
For the sake of completeness
val testTxtSource = scala.io.Source.fromFile("test.txt")
val str = testTxtSource.mkString()
testTxtSource.close()
Should get things done.
回答2:
Scala's io
library was just hack done to provide support for limited needs. There was an effort to provide a well-thought io library to Scala, which is currently hosted at assembla, with a github repository as well.
If you are going to use I/O for anything more than reading the occasional file on short-lived processes, you'd better either use Java libraries, or look at the I/O support presently available in the compiler (which will require scala-compiler.jar to be distributed with the app).
As for automatic resource management, look at this question, or at this library (which is featured in the accepted answer at that question).
回答3:
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")
回答4:
I recommend using the using, which makes your code neater and more reliable
using(Source.fromFile("test.txt")){ _.mkString()}
来源:https://stackoverflow.com/questions/4458864/whats-the-right-way-to-use-scala-io-source