Scala Code For Reading File

DeeKay February 4, 2011 at 6:44 pm · Code Examples

There are many ways reading file in using Scala language. I will walk-through the options available for reading the file. If anyone wants to add improvements in below code example please feel to add it in the comment. This Scala code is tested on large file and it works fine.


/**
* Scala code to read the file contents and prints on console.
*/
package com.demo

/**
* @author http://kodehelp.com
*
*/
object ReadFile {

def main(args: Array[String]) {

val lines = io.Source.fromFile("/demo.dat","utf-8").getLines
while(lines.hasNext){
println(lines.next);
}

}
}

Other option with smaller syntax is shown below :


for {(line) <- io.Source.fromFile("/demo.dat").getLines}
println(line)