Writing Files in Scala

Here’s the translation of the Go code to Scala, with explanations in Markdown format suitable for Hugo:

Writing files in Scala follows similar patterns to the ones we saw earlier for reading.

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

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

  def main(args: Array[String]): Unit = {
    // To start, here's how to dump a string (or just bytes) into a file.
    val d1 = "hello\nscala\n".getBytes
    try {
      Files.write(Paths.get("/tmp/dat1"), d1)
    } catch {
      case e: Throwable => check(e)
    }

    // For more granular writes, open a file for writing.
    val f = new File("/tmp/dat2")
    val writer = new FileWriter(f)

    // It's idiomatic to use a try-finally block to ensure the file is closed.
    try {
      // You can write byte arrays as you'd expect.
      val d2 = Array[Byte](115, 111, 109, 101, 10)
      writer.write(new String(d2))
      println(s"wrote ${d2.length} bytes")

      // A write method for strings is also available.
      val n3 = writer.write("writes\n")
      println(s"wrote $n3 bytes")

      // Flush writes to ensure they're written to the file.
      writer.flush()

      // BufferedWriter provides buffered writers in addition
      // to the buffered readers we saw earlier.
      val bufferedWriter = new BufferedWriter(writer)
      val n4 = bufferedWriter.write("buffered\n")
      println(s"wrote $n4 bytes")

      // Use flush to ensure all buffered operations have
      // been applied to the underlying writer.
      bufferedWriter.flush()
    } finally {
      writer.close()
    }
  }
}

Try running the file-writing code.

$ scala WritingFiles.scala
wrote 5 bytes
wrote 7 bytes
wrote 9 bytes

Then check the contents of the written files.

$ cat /tmp/dat1
hello
scala
$ cat /tmp/dat2
some
writes
buffered

Next we’ll look at applying some of the file I/O ideas we’ve just seen to the stdin and stdout streams.