Scala – Files I/O

  • Post category:Scala
  • Reading time:4 mins read

How to read / write files using Scala ?

Scala can use existing Java classes to read and write files. The following is an example program to writing to a file.

Example

import java.io._
object Demo {
   def main(args: Array[String]) {
      val writer = new PrintWriter(new File("readMe.txt" ))
      writer.write("Hello World")
      writer.close()
   }
}

Save the above program in file Demo.scala. Below mentioned commands are used to compile and run this program.

scalac Demo.scala
scala Demo

It will create a file named readMe.txt in the current directory with the content “Hello World”.

How to read a file from Command Line ?

We can use Console class to read input from the command line.

Example

object ConsoleReader{
   def main(args: Array[String]) {
      print("Please enter your input : " )
      val line = Console.readLine
      println("Thanks, you just typed: " + line)
   }
}

Save the above program in ConsoleReader.scala. The following commands are used to compile and execute this program.

scalac ConsoleReader.scala
scala ConsoleReader

Reading File Content

Reading from files is really simple. You can use Scala’s Source class and its companion object to read files. Following is the example which shows you how to read from “Demo.txt” file which we created earlier.

import scala.io.Source
object MyFileReader{
   def main(args: Array[String]) {
      println("Reading the file :" )
      Source.fromFile("readMe.txt" ).foreach { 
         print 
      }
   }
}

Save the above program in MyFileReader.scala. The following commands are used to compile and execute this program.

scalac MyFileReader.scala
scala MyFileReader

Reading File Content – Char by Char

import scala.io.Source
object MyFileReader{
   def main(args: Array[String]) {
      val file = Source.fromFile("readMe.txt")
      while (file.hasNext) {
         println(file.next)
      }
   }
}

Save the above program in MyFileReader.scala. The following commands are used to compile and execute this program.

scalac MyFileReader.scala
scala MyFileReader

Reading File Content – Line by Line

import scala.io.Source
object MyFileReader{
   def main(args: Array[String]) {
          val file = Source.fromFile("readMe.txt")
          for(line <- file.getLines){
             println(line)
          }
   }
}

Save the above program in MyFileReader.scala. The following commands are used to compile and execute this program.

scalac MyFileReader.scala
scala MyFileReader