What's the right way to use scala.io.Source?

血红的双手。 提交于 2019-11-30 01:37:30

For the sake of completeness

val testTxtSource = scala.io.Source.fromFile("test.txt")
val str = testTxtSource.mkString()
testTxtSource.close()

Should get things done.

Daniel C. Sobral

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).

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")
Valentin Tihomirov

I recommend using the using, which makes your code neater and more reliable

using(Source.fromFile("test.txt")){ _.mkString()}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!