Vasco Pereira
Vasco Pereira

Reputation: 47

How to read a resource file to a byte array in scala?

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

Upvotes: 5

Views: 5136

Answers (2)

poki2
poki2

Reputation: 71

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()

Upvotes: 3

Norwæ
Norwæ

Reputation: 1575

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()
}

Upvotes: 2

Related Questions