I just want to read file in resource and get a byte array? Can someone help me with that?
Asked
Active
Viewed 4,701 times
5
-
1Almost 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 Answers
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()
}
-
This approach is very slow and heavy on CPU, because it reads the file byte by byte, one byte at a time. – m.bemowski Sep 27 '18 at 14:28