Scala program to read data from a text file

Here, we are going to learn how to read data from a text file in Scala programming language?
Submitted by Nidhi, on July 16, 2021 [Last updated : March 11, 2023]

Scala - Read Data from a File

Here, we will read data from file character by character and print data on the console screen.

Scala code to read data from a text file

The source code to read data from a text file is given below. The given program is compiled and executed on the ubuntu 18.04 operating system successfully.

// Scala program to read data from a text file

import scala.io.Source;

object Sample {
  // Main method
  def main(args: Array[String]) {
    val file = Source.fromFile("Sample.txt")

    println("Data of file:");
    while (file.hasNext) {
      print(file.next)
    }
    file.close();
    println();
  }
}

Output

Data of file:
Hello World

Explanation

In the above program, we used an object-oriented approach to create the program. We imported the Source class using the below statement.

import scala.io.Source;

And, we created a singleton object Sample and defined the main() function. The main() function is the entry point for the program.

In the main() function, we used the fromFile() method of the Source class to create the object. Then read data from file character by character using the next() method and printed the data on the console screen.

Scala File Handling Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.