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);
}
}



An even smaller and more idiomatic way:
val s = Source.fromFile(“/demo.dat”).mkString
println(s)
An even smaller and more idiomatic way:
val s = Source.fromFile(“/demo.dat”).mkString
println(s)
Why two lines and the val:
println(val s = Source.fromFile(“/demo.dat”).mkString)
Why two lines and the val:
println(val s = Source.fromFile(“/demo.dat”).mkString)
He said and left the val in …..
println(Source.fromFile(“/demo.dat”).mkString)
He said and left the val in …..
println(Source.fromFile(“/demo.dat”).mkString)
This will result in loading the entire file into memory. Twice, in fact. Once as a list of the lines of the file and again as a single string. Given that the subject of the post referred to large file I think that this isn’t a good solution to the problem.
This will result in loading the entire file into memory. Twice, in fact. Once as a list of the lines of the file and again as a single string. Given that the subject of the post referred to large file I think that this isn’t a good solution to the problem.
io.Source.fromFile(“/demo.dat”,”utf-8″).getLines.foreach(println)
io.Source.fromFile(“/demo.dat”,”utf-8″).getLines.foreach(println)
@Doug – Can you let me us know the good solution for reading large file in scala?
@Doug – Can you let me us know the good solution for reading large file in scala?