Enrollments closing soon for Post Graduate Certificate Program in Applied Data Science & AI By IIT Roorkee | 3 Seats Left

  Apply Now

Scala

47 / 53

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")
      writer.close()
   }
}

To write to this file execute the object by

IOTest.main(Array())

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 { 
         print 
      }
   }
}

Another to read the file content:

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

No hints are availble for this assesment

Answer is not availble for this assesment

Loading comments...