Read a File in Scala – [How To]

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

12 comments

  1. Haakon says:

    An even smaller and more idiomatic way:

    val s = Source.fromFile(“/demo.dat”).mkString
    println(s)

  2. Haakon says:

    An even smaller and more idiomatic way:

    val s = Source.fromFile(“/demo.dat”).mkString
    println(s)

  3. Ingo Boegemann says:

    Why two lines and the val:
    println(val s = Source.fromFile(“/demo.dat”).mkString)

  4. Ingo Boegemann says:

    Why two lines and the val:
    println(val s = Source.fromFile(“/demo.dat”).mkString)

  5. Ingo Boegemann says:

    He said and left the val in …..
    println(Source.fromFile(“/demo.dat”).mkString)

  6. Ingo Boegemann says:

    He said and left the val in …..
    println(Source.fromFile(“/demo.dat”).mkString)

  7. DougC says:

    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.

  8. DougC says:

    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.

  9. Daniel Lundin says:

    io.Source.fromFile(“/demo.dat”,”utf-8″).getLines.foreach(println)

  10. Daniel Lundin says:

    io.Source.fromFile(“/demo.dat”,”utf-8″).getLines.foreach(println)

  11. Info says:

    @Doug – Can you let me us know the good solution for reading large file in scala?

  12. Info says:

    @Doug – Can you let me us know the good solution for reading large file in scala?

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *