Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 697
woods Avatar asked Dec 16 '10 08:12

woods


People also ask

What is Scala io?

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.


1 Answers

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") 
like image 151
Xavier Guihot Avatar answered Sep 21 '22 07:09

Xavier Guihot