...

Cloud Computing - SCALA

Back to Course

Lesson Description


Lession - #698 SCALA FILE IO


Scala is available to utilize any Java objects and java.io.File is one of the items which can be utilized in Scala programming to read and write files.

SComing up next is a model program to keeping in touch with a document.


Model
import java.io._

object Demo {
   def main(args: Array[String]>
{ val writer = new PrintWriter(new File("test.txt" >
>
writer.write("Hello Scala">
writer.close(>
} }


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

Command

\>scalac Demo.scala
\>scala Demo

Output

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

Reading File Content
SReading 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