ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

Scala program to read data from a file line by line

Here, we are going to learn how to read data from a file line by line in Scala programming language?
Submitted by Nidhi, on July 16, 2021

Problem Solution:

In this program, we will read data from a file line by line using the getLines() method and print data on the console screen.

Program/Source Code:

The source code to read data from a file line by line 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 file 
// line by line

import scala.io.Source;

object Sample {
  // Main method
  def main(args: Array[String]) {

    val file = Source.fromFile("Sample.txt")

    println("Data of file:");

    //Read data from file line by line.
    for (line <- file.getLines) {
      println(line)
    }

    file.close();
  }
}

Output:

Data of file:
Text Line1
Text Line2
Text Line3
Text Line4

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 an object. Then read data from a file line by line using the getLines() method and printed the data on the console screen.

Scala File Handling Programs »


ADVERTISEMENT



ADVERTISEMENT



Comments and Discussions

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.