How to read a file as a byte array in Scala How to read a file as a byte array in Scala arrays arrays

How to read a file as a byte array in Scala


Java 7:

import java.nio.file.{Files, Paths}val byteArray = Files.readAllBytes(Paths.get("/path/to/file"))

I believe this is the simplest way possible. Just leveraging existing tools here. NIO.2 is wonderful.


This should work (Scala 2.8):

val bis = new BufferedInputStream(new FileInputStream(fileName))val bArray = Stream.continually(bis.read).takeWhile(-1 !=).map(_.toByte).toArray


val is = new FileInputStream(fileName)val cnt = is.availableval bytes = Array.ofDim[Byte](cnt)is.read(bytes)is.close()