Halloween Sale: Flat 70% + Addl. 25% Off + 30 Days Extra Lab on all Courses | Use Coupon HS25 in Checkout | Offer Expires In

  Enroll Now

Scala - File IO

Writing to a file

Scala uses java.io.File class to write the files to the operating system.
A File object is created followed by an object of PrintWriter class. The write function of PrintWriter class does the writing to the file.

Below example create a new File object and writes the lines to it.

import java.io._
object IOTest {
   def main(args: Array[String]) {
      val writer = new PrintWriter(new File("new.txt" ))

      writer.write("Hello There Scala")

To write to this file execute the object by


Reading from a file

Scala uses scala.io.Source class to read the files from the operating system.

Below example create a new "IOTest" object and read the contents from "new.txt" lines to it.

import scala.io.Source
object IOTest {
   def main(args: Array[String]) {
      println("Content of the file is:" )
      Source.fromFile("new.txt" ).foreach { 

Another to read the file content:

import scala.io.Source;
for (line <-Source.fromFile("new.txt").getLines) {

No hints are availble for this assesment

Answer is not availble for this assesment

Loading comments...