There are many ways to read files in using Scala language. I will walk through the options available for reading the file.
If anyone wants to add improvements to the below code example please feel to add it in the comment. This Scala code is tested on a large file and it works fine.
/**
* Scala code to read the file contents and prints on console.
*/
package com.demo
/**
* @author https://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 :
/**
* Scala code to read the file contents and prints on console.
*/
package com.demo
/**
* @author https://kodehelp.com
*
*/
object ReadFile {
def main(args: Array[String]) {
io.Source.fromFile(“/demo.dat”,”utf-8″).getLines.foreach(println);
}
}