September 2015
Intermediate to advanced
250 pages
6h 40m
English
Now that you know how to get user input in Scala, it’s time to see how to write data to a file. We can use the java.io.File object to achieve this. Here’s an example of writing to a file:
| UsingScala/WriteToFile.scala | |
| | import java.io._ |
| | |
| | val writer = new PrintWriter(new File("symbols.txt")) |
| | writer write "AAPL" |
| | writer.close() |
This simple code writes the symbol “AAPL” to the file named symbols.txt.
Reading files is really simple as well. Scala’s Source class and its companion object come in handy for this purpose. For illustration purposes, let’s write a Scala script that reads itself:
| UsingScala/ReadingFile.scala | |
| | import scala.io.Source |
| | |
| | println("*** The content of the file you read is:") |
| | Source.fromFile( ... |
Read now
Unlock full access