×

Scala Tutorial

Scala Basics

Scala Control statements

Scala Functions

Scala Arrays

Scala Lists

Scala Strings

Scala Classes & Objects

Scala Collections

How to read entire file in Scala?

By IncludeHelp Last updated : November 16, 2024

Reading a file

Reading contents of a file is a part of file handling in Scala and is used to read data.

You can access the data of a file and use it in your program.

Scala code to read entire file

Here is the code used to read entire file in Scala,

import scala.io.Source

object MyClass {
  def main(args: Array[String]): Unit = {
    val filename = "fileopen.scala"
    
    try {
      val source = Source.fromFile(filename)
      try {
        for (line <- source.getLines) {
          println(line)
        }
      } finally {
        source.close() // Ensure the file is closed after use
      }
    } catch {
      case ex: Exception => 
        println(s"Error: Could not read file '$filename'. ${ex.getMessage}")
    }
  }
}

Output

Contents of file...

Comments and Discussions!

Load comments ↻





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