How to Read/Write Files with Scala

Advertisement

Advertisement

Scala provides some of its own libraries for IO, but we can also make use of the Java library. The example of reading a file uses Scala's IO package, but the file writing example uses the Java IO package.

Reading a File

import scala.io.Source

object ReadLineFile {
    def main(args: Array[String]) {

        // Loop through each line in the file
        for (line <- Source.fromFile("test.txt").getLines()) {
            // Do something with line
            println(line)
        }

    }
}

Writing a File

import java.io._

object WriteFile {
   def main(args: Array[String]) {

      val writer = new PrintWriter(new File("output.txt"))
      writer.write("Hello, world!")
      writer.close()

   }
}

Advertisement

Advertisement