00.scala2014. 3. 28. 15:38
반응형

Scala file FAQ: How do I open and read files in Scala?

When you're writing Scala scripts, you often want to read text files. Fortunately it's pretty easy to openand read from a file in Scala. You can just use an approach like this:

import scala.io.Source

val filename = "fileopen.scala"
for (line <- Source.fromFile(filename).getLines()) {
  println(line)
}

As you can see, this approach uses the scala.io.Source class. Within the for loop I can now access each line of the file using the 'line' object, and in this case I'm printing each line using println.

A variation of this is to add the mkString function to the file-reading portion of that code, like this:

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

Another nice file-reading example comes from Bruce Eckel's website:

val fileLines = io.Source.fromFile("Colors.scala").getLines.toList
fileLines.foreach(println)

As you can see from that example, you can read an entire text file into a Scala List with what appears to be only one line of source code.

Handling file exceptions

Of course you can generate exceptions when trying to open a file, and if you want to handle your exceptions, you use a syntax similar to the Java try/catch syntax, like this:

import scala.io.Source

val filename = "no-such-file.scala"
try {
  for (line <- Source.fromFile(filename).getLines()) {
    println(line)
  }
} catch {
  case ex: Exception => println("Bummer, an exception happened.")
}

If I change that Exception line to print my exception object, like this:

case ex: Exception => println(ex)

and then run this script again, I can see that this code throws a java.io.FileNotFoundException exception when it fails:

java.io.FileNotFoundException: no-such-file.scala (No such file or directory)

As a result, if I want to catch all the old Java exceptions like I used to, I can write a Scala script like this to catch the Java FileNotFoundException and IOException:

import scala.io.Source
import java.io.{FileReader, FileNotFoundException, IOException}

val filename = "no-such-file.scala"
try {
for (line <- Source.fromFile(filename).getLines()) {
  println(line)
}
} catch {
  case ex: FileNotFoundException => println("Couldn't find that file.")
  case ex: IOException => println("Had an IOException trying to read that file")
}


Posted by 1010