Scala

Read a File in Scala – [How To]

Scala Language

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. Ingo Boegemann ·

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

  2. Ingo Boegemann ·

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

  3. Ingo Boegemann ·

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

  4. Ingo Boegemann ·

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

  5. 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.

  6. 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.

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

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

Leave a Comment

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