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.
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.
\>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.
Hello Scala
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.
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.
\>scalac Demo.scala \>scala Demo
Please enter your input : Scala is great Thanks, you just typed: Scala is great
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 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.
\>scalac Demo.scala \>scala Demo
Following is the content read: Hello Scala