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:

import scala.io.Source

val filename = "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:

val lines = Source.fromFile("/Users/Al/.bash_profile").getLines.toList
val lines = 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:

val fileContents = Source.fromFile(filename).getLines.mkString

This approach has the side effect of leaving the file ...

Get Scala Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.