Scala

45 / 51
   

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()
   }
}

Reading from a file

Scala uses scala.io.Source class to read the files from 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 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)
}