O'Reilly logo

Pragmatic Scala by Venkat Subramaniam

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Reading and Writing Files

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(​ ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required