Tuesday, September 13, 2016

File I/O Example...

scala> /*
     |     Method 1 : Using List #96
     | */
     | import scala.io.Source
import scala.io.Source

scala> val source = Source.fromFile("./data.txt")
source: scala.io.BufferedSource = non-empty iterator

scala> //Load the entire file into List

scala> //Disadvatnage : Entire File is loaded into Memory

scala> val lines = source.getLines().toList
lines: List[String] = List(line 1, line 2, A long line....)

scala>

scala> /*
     |     Method 2 : Using Iterator
     | */
     | import scala.io.Source
import scala.io.Source

scala> val source = Source.fromFile("./data.txt")
source: scala.io.BufferedSource = non-empty iterator

scala> //An iterator can be iterated only once, after that it is spent

scala> //Advantage : The complete file is not loaded into Memory

scala> val iter = source.getLines()
iter: Iterator[String] = non-empty iterator

scala> for (line <- iter){
     |     println(line)
     | }
line 1
line 2
A long line....