Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read a file as a byte array in Scala

I can find tons of examples but they seem to either rely mostly on Java libraries or just read characters/lines/etc.

I just want to read in some file and get a byte array with scala libraries - can someone help me with that?

like image 898
fgysin Avatar asked Sep 29 '11 13:09

fgysin


2 Answers

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.

like image 189
Vladimir Matveev Avatar answered Oct 18 '22 11:10

Vladimir Matveev


This should work (Scala 2.8):

val bis = new BufferedInputStream(new FileInputStream(fileName))
val bArray = Stream.continually(bis.read).takeWhile(-1 !=).map(_.toByte).toArray
like image 47
Jus12 Avatar answered Oct 18 '22 13:10

Jus12