Scala - Files I/O


Advertisements

Scala is open to make use of any Java objects and java.io.File is one of the objects which can be used in Scala programming 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("test.txt" ))

      writer.write("Hello Scala")
      writer.close()
   }
}

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

Command

\>scalac Demo.scala
\>scala Demo

It will create a file named Demo.txt in the current directory, where the program is placed. The following is the content of that file.

Output

Hello Scala

Reading a Line from Command Line

Sometime you need to read user input from the screen and then proceed for some further processing. Following example program shows you how to read input from the command line.

Example

object Demo {
   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 Demo.scala. The following commands are used to compile and execute this program.

Command

\>scalac Demo.scala
\>scala Demo

Output

Please enter your input : Scala is great
Thanks, you just typed: Scala is great

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.

Example

import scala.io.Source

object Demo {
   def main(args: Array[String]) {
      println("Following is the content read:" )

      Source.fromFile("Demo.txt" ).foreach { 
         print 
      }
   }
}

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

Command

\>scalac Demo.scala
\>scala Demo

Output

Following is the content read:
Hello Scala
Advertisements