Scala File Input and Output

Education is not limited to just classrooms. It can be gained anytime, anywhere... - Ravi Ranjan (M.Tech-NIT)

Scala File Input and Output

File operations mostly includes reading data from file or writing data into files.

 

Writing Data form File

e.g.

import java.io._

object Intellipaat {

def main(args: Array[String]) {

val writer = new PrintWriter(new File("intellipaat.txt" ))

writer.write("Hello Intellipaat")

writer.close()

}

}

When we compile and execute this program then it write Hello Intellipaat in intellipaat.txt file.

 

Reading Data from File

e.g.

import scala.io.Source

object Intellipaat {

def main(args: Array[String]) {

println("Data in File is:" )

Source.fromFile("intellipaat.txt" ).foreach{

print

}

}

}

Compile and execute the above program:

scalac Intellipaat.scala

scala Intellipaat

Output

Data in file is: Hello Intellipaat