Lesson contents

Scala — Managing files with Using.resource

Scala Using.resource closes a Source after the supplied function finishes. Read and process the lines inside that function while the resource is open.

A simple example

Read back one letter

  1. Start with A
  2. Do this Write, then read
  3. Result A
A file stores the letter between the write and the read.
Lesson.scala
import java.nio.file.Files
object Lesson extends App {
    val path = Files.createTempFile("letter", ".txt")
    try {
        Files.writeString(path, "A")
        println(Files.readString(path))
    } finally {
        Files.delete(path)
    }
}
Output
A
Advertisements

Sum two lines from a temporary report

Using.resource closes the Source as soon as the sum completes. The outer finally removes the path. Using is available in Scala 2.13 and Scala 3, and Files.writeString needs JDK 11 or later.

Morning returns: 4. Afternoon returns: 7. End of day: 11.
Read a two-line count sheet

Morning staff record four returns in a file and afternoon staff record seven on the next line. Read each line as a number and add it to the running total. The day ends with eleven returns.

Run the example

Scala 2.13 with JDK 11 or later. Run these commands from the directory containing the example.

scalac Lesson.scala
scala Lesson
Lesson.scala
object Lesson {
  import java.nio.file.Files
  import scala.io.Source
  import scala.util.Using

  def main(args: Array[String]): Unit = {
    val path = Files.createTempFile("readings", ".txt")
    try {
      Files.writeString(path, "4\n7\n")
      val total = Using.resource(Source.fromFile(path.toFile, "UTF-8")) { source =>
        source.getLines().map(_.trim).filter(_.nonEmpty).map(_.toInt).sum
      }
      println(total)
    } finally {
      Files.deleteIfExists(path)
    }
  }
}
Output
11

The file contains two whole-number readings on separate lines. Reading from the beginning gives 4 and 7, for a total of 11. The example creates its own file, so it can run in a clean working directory.

Try it yourself

Add a third line containing 12.

Check your answer

The new total is 23. This report format assumes valid integer readings. When accepting external input, apply the validation techniques from the preceding lesson.

Tour of Scala

Related tags

  • Scala
  • files
  • streams
  • resource management