0

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.

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
fscore
  • 2,567
  • 7
  • 40
  • 74

3 Answers3

1

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")
fscore
  • 2,567
  • 7
  • 40
  • 74
1

The issue here is that /src is probably the root of classpath (it depends on how you compile the project), and so you should put the img.png to src folder and the following code would work

DataService.class.getResourceAsStream("img.png");

Generally the getResourceAsStream() looks for the files from the root of classpath.

ikryvorotenko
  • 1,393
  • 2
  • 16
  • 27
0

you just need to do a small change, it's getResourceAsStream("/img.png") not getResourceAsStream("img.png").

I hope this will help.

Dimitrios Begnis
  • 823
  • 6
  • 16
  • Did not work with that change – fscore Mar 31 '16 at 16:41
  • Are you sure than, that the NPE is because of image path ? Because the following works perfectly fine for me: `BufferedImage img = ImageIO.read(DataService.class.getResourceAsStream("/img.jpg")); if (img != null) { System.out.println(" not null"); }` – Dimitrios Begnis Mar 31 '16 at 16:51