Artem Moskalev
Artem Moskalev

Reputation: 5818

Cannot find the image in the java dynamic web project

I have the following problem:

I created the servlet which should draw a dynamic graph. During the drawing process it should fetch the picture from another directory and to draw it upon another image. Everything should work fine:

try {
            BufferedImage temp = ImageIO.read(new File("image/arrow.png"));
            tempIm = temp.getScaledInstance(55, 55, Image.SCALE_SMOOTH);
        } catch (IOException e) {

            e.printStackTrace();

        }

But it prints the following:

SEVERE: javax.imageio.IIOException: Can't read input file! at javax.imageio.ImageIO.read(ImageIO.java:1275) at CertificateDraw.doGet(CertificateDraw.java:36)

I tried to change the path of the File object in all possible ways it just gives the same problem even though the part of the image is still sent to the browser. So the problem is with the ImageIO.read part - how can I find why it does not load the image?!

I am working in Eclipse - servlet is in the src folder. The image is in "image" folder under the rot directory "WebContent".

Upvotes: 1

Views: 1755

Answers (1)

BalusC
BalusC

Reputation: 1108692

Relative paths in java.io.File are relative to the current working directory (CWD). This is the folder which is currently opened when the command is given to start the Java runtime environment (in your case, the webserver). When starting the server in Eclipse, this is usually the /bin folder of the project. You can figure this by printing new File(".").getAbsolutePath().

But you shouldn't be relying on relative paths in File at all. The CWD is not controllable from inside the code.

As it's in the webcontent folder already, just get it by ServletContext#getResourceAsStream() instead.

InputStream input = getServletContext().getResourceAsStream("/image/arrow.png");
BufferedImage image = ImageIO.read(input);
// ...

Note that the getServletContext() is inherited from the GenericServlet class which the HttpServlet extends from, so you don't need to provide the method yourself.

Upvotes: 1

Related Questions