getResourceAsStream returns NullpointerException
<p>In Spring, I want to get the image to display on my browser.  The image is located in my main project i.e.</p>
<pre><code>&gt; myproject
   - src
   - target
   - img.png
</code></pre>
<p>This means that img.png is in the root so I dont supply any path but it returns a <code>NullPointerException</code>. I tried adding the image in src and I changed path to <code>src\img.png</code> but still gave NPE.</p>
<p>Please note, this project is using Maven.</p>
<p>Stack Trace:</p>
<pre><code>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]
</code></pre>
<p>Here is the code I use:</p>
<pre><code>InputStream in = DataService.class.getResourceAsStream(&quot;img.png&quot;);

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

        result.setData(new ResponseEntity&lt;byte[]&gt;(IOUtils.toByteArray(in), headers, HttpStatus.CREATED));
</code></pre>
<p><strong>Comments on this question being marked for closure:</strong></p>
<ul>
<li>The question is related to programming as the API <a href="https://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29" rel="nofollow noreferrer">getResourceAsStream</a> says this:</li>
</ul>
<blockquote>
<p>Returns
A URL object or null if no resource with this name is found</p>
</blockquote>
<p>My code was returning <code>null</code> even when I tried adding <code>img.png</code> to different locations.</p>
<ul>
<li>This question is not a duplicate of this: <a href="https://stackoverflow.com/questions/2797162/getresourceasstream-is-always-returning-null">getResourceAsStream() is always returning null</a></li>
</ul>
<p>The answer in that question says that the file must be in the same directory as <code>this</code> but in this question, even though I added the image to the same location where class <code>DataService</code> was, it did not work.</p>