Scala: read a file into memory

To read in an entire file in Scala, you can use Java APIs, but by initializing data structures in a different way – note how the byte array is created.

try {
  val file = new File("src/main/scala/Main.scala")
  val fis = new FileInputStream(file)

  val data = Array.fill[Byte](file.length.toInt)(0)
  fis.read(data)
  fis.close

  val str = new String(data, "UTF-8")

  print(str)
} catch {
  case e: Exception => {
    println(e)
  }
}

Also of interest is the exception block – this uses pattern matching, which makes it look more like a case statement in Java.

Leave a Reply

Your email address will not be published. Required fields are marked *