javaspring-bootinputstreamrequest-mapping

getResourceAsStream returns NullpointerException


In Spring, I want to get the image to display on my browser. The image is located in my main project i.e.

> myproject
   - src
   - target
   - img.png

This means that img.png is in the root so I dont supply any path but it returns a NullPointerException. I tried adding the image in src and I changed path to src\img.png but still gave NPE.

Please note, this project is using Maven.

Stack Trace:

java.lang.NullPointerException: null
    at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1792) ~[commons-io-2.4.jar:2.4]
    at org.apache.commons.io.IOUtils.copyLarge(IOUtils.java:1769) ~[commons-io-2.4.jar:2.4]
    at org.apache.commons.io.IOUtils.copy(IOUtils.java:1744) ~[commons-io-2.4.jar:2.4]
    at org.apache.commons.io.IOUtils.toByteArray(IOUtils.java:462) ~[commons-io-2.4.jar:2.4]

Here is the code I use:

InputStream in = DataService.class.getResourceAsStream("img.png");

        final HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_PNG);

        result.setData(new ResponseEntity<byte[]>(IOUtils.toByteArray(in), headers, HttpStatus.CREATED));

Comments on this question being marked for closure:

Returns A URL object or null if no resource with this name is found

My code was returning null even when I tried adding img.png to different locations.

The answer in that question says that the file must be in the same directory as this but in this question, even though I added the image to the same location where class DataService was, it did not work.


Solution

  • When the project setup is done using Maven, adding the image to resources folder worked. Nothing from the code changed:

    DataService.class.getClassLoader().getResource("img.png")