Temporary Files And Directories in Scala

Throughout program execution, we often want to create data that isn’t needed after the program exits. Temporary files and directories are useful for this purpose since they don’t pollute the file system over time.

import java.io.{File, FileWriter}
import java.nio.file.{Files, Paths}

object TemporaryFilesAndDirectories extends App {

  def check(e: Throwable): Unit = {
    if (e != null) {
      throw e
    }
  }

  // The easiest way to create a temporary file in Scala is by
  // using Files.createTempFile. It creates a file and returns
  // its path. We provide null as the first argument, so it will
  // create the file in the default location for our OS.
  val tempFile = Files.createTempFile(null, "sample")
  
  // Display the name of the temporary file. On
  // Unix-based OSes the directory will likely be `/tmp`.
  // The file name starts with the prefix given as the
  // second argument and the rest is chosen automatically to
  // ensure that concurrent calls will always create different file names.
  println(s"Temp file name: ${tempFile.toString}")

  // Clean up the file after we're done. The OS is
  // likely to clean up temporary files by itself after
  // some time, but it's good practice to do this
  // explicitly.
  tempFile.toFile.deleteOnExit()

  // We can write some data to the file.
  val writer = new FileWriter(tempFile.toFile)
  writer.write(Array(1, 2, 3, 4).map(_.toByte))
  writer.close()

  // If we intend to write many temporary files, we may
  // prefer to create a temporary *directory*.
  // Files.createTempDirectory's arguments are similar to
  // createTempFile's, but it returns a directory *path*
  // rather than a file path.
  val tempDir = Files.createTempDirectory("sampledir")
  println(s"Temp dir name: ${tempDir.toString}")

  tempDir.toFile.deleteOnExit()

  // Now we can synthesize temporary file names by
  // prefixing them with our temporary directory.
  val fname = Paths.get(tempDir.toString, "file1").toString
  Files.write(Paths.get(fname), Array[Byte](1, 2))
}

To run the program, save it as TemporaryFilesAndDirectories.scala and use scala:

$ scala TemporaryFilesAndDirectories.scala
Temp file name: /tmp/sample8217676152135918008
Temp dir name: /tmp/sampledir3506281155871975636

In this Scala version, we use Files.createTempFile and Files.createTempDirectory from the java.nio.file package to create temporary files and directories. The deleteOnExit() method is used to ensure cleanup, similar to the defer statements in the original code. We use FileWriter for writing to the file, and Files.write for writing to a file in the temporary directory.

The overall structure and functionality remain the same as the original example, adapted to Scala’s syntax and standard library.