5

I just want to read file in resource and get a byte array? Can someone help me with that?

Vasco Pereira
  • 47
  • 1
  • 3
  • 1
    Almost a duplicate of http://stackoverflow.com/questions/27360977/how-to-read-files-from-resources-folder-in-scala?rq=1 (that one tries to read lines instead of bytes, but maybe you can adapt it, for example by combining it with http://stackoverflow.com/questions/7598135/how-to-read-a-file-as-a-byte-array-in-scala) – Thilo Nov 17 '15 at 11:19

2 Answers2

3

Note: this requires Java 9+

I use the following to read a file in my resources as byte array:

getClass.getResourceAsStream("/file-in-resource-folder").readAllBytes()
poki2
  • 71
  • 5
2

As described in How to read a file as a byte array in Scala, the following fragment should do the trick:

def slurp(resource: String) = {
  val bis = new BufferedInputStream(getClass.getResource(resource))
  try Stream.continually(bis.read).takeWhile(-1 !=).map(_.toByte).toArray
  finally bis.close()
}
Community
  • 1
  • 1
Norwæ
  • 1,575
  • 8
  • 18