12.1. How to Open and Read a Text File
Problem
You want to open a plain-text file in Scala and process the lines in that file.
Solution
There are two primary ways to open and read a text file:
Use a concise, one-line syntax. This has the side effect of leaving the file open, but can be useful in short-lived programs, like shell scripts.
Use a slightly longer approach that properly closes the file.
This solution shows both approaches.
Using the concise syntax
In Scala shell scripts, where the JVM is started and stopped in
a relatively short period of
time, it may not matter that the file is closed, so you can
use the Scala scala.io.Source.fromFile method as shown in
the following examples.
To handle each line in the file as it’s read, use this approach:
importscala.io.Sourcevalfilename="fileopen.scala"for(line<-Source.fromFile(filename).getLines){println(line)}
As a variation of this, use the following approach to get all of
the lines from the file as a List
or Array:
vallines=Source.fromFile("/Users/Al/.bash_profile").getLines.toListvallines=Source.fromFile("/Users/Al/.bash_profile").getLines.toArray
The fromFile method returns a
BufferedSource, and its getLines method treats “any of \r\n, \r,
or \n as a line separator (longest
match),” so each element in the sequence is a line from the
file.
Use this approach to get all of the lines from the file as one
String:
valfileContents=Source.fromFile(filename).getLines.mkString
This approach has the side effect of leaving the file ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access