3

I made a /header folder in the web pages directory in Netbeans and added an image named header.png. Now I want to access this image file in a servlet using the following code:

BufferedImage image = ImageIO.read(getClass().getResource(" /header/header.png"));

But this is not happening, it gives the following error:

java.lang.IllegalArgumentException: input == null!

Below is my project's directory structure:

enter image description here

How is this error caused and how can I solve it?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
Amit
  • 233
  • 1
  • 5
  • 9
  • 1
    Please don't repost the same question over and over: http://stackoverflow.com/questions/13640602/image-is-not-loading-from-project-classpath-giving-error-java-lang-illegalargum If you think you question can be improved, edit it. Or if you can't seem to find it back, then click on your username link in the top bar, it'll lead you to your user profile where you can find all your previously asked questions. – BalusC Nov 30 '12 at 15:05

1 Answers1

1

The Class#getResource() returns an resource from the class path, not from the public web content.

You need ServletContext#getResource(), or better, getResourceAsStream() instead.

BufferedImage image = ImageIO.read(getServletContext().getResourceAsStream("/header/header.png"));

(note that I removed the trailing space from the path as well)

Note that some users may suggest you to use ServletContext#getRealPath(), but you shouldn't use it in this particular case as that may return null when the container is configured to expand the deployed WAR into memory instead of local disk file system.

See also:

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555