Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to load a classpath resource to an array of byte?

I know how to get the inputstream for a given classpath resource, read from the inputstream until i reach the end, but it looks like a very common problem, and i wonder if there an API that I don't know, or a library that would make things as simple as

byte[] data = ResourceUtils.getResourceAsBytes("/assets/myAsset.bin") 

or

byte[] data = StreamUtils.readStreamToEnd(myInputStream) 

for example!

like image 469
Samuel Rossille Avatar asked May 30 '12 08:05

Samuel Rossille


People also ask

How do I load resources from classpath?

We can either load the file(present in resources folder) as inputstream or URL format and then perform operations on them. So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.

How do you assign a byte array?

Arrays. fill(). This method assigns the required byte value to the byte array in Java. The two parameters required for java.

What is ClassPathResource in spring?

ClassPathResource ClassPathResource is a Resource implementation for class path resources. It supports resolution as java. io. File if the class path resource resides in the file system, but not for resources in a JAR.

What is classpath resource in Java?

Classpath in Java is not only used to load . class files, but also can be used to load resources e.g. properties files, images, icons, thumbnails, or any binary content. Java provides API to read these resources as InputStream or URL.


1 Answers

Java 9 native implementation:

byte[] data = this.getClass().getClassLoader().getResourceAsStream("/assets/myAsset.bin").readAllBytes(); 
like image 84
Marek Gregor Avatar answered Sep 17 '22 11:09

Marek Gregor