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”.
Relative paths in
java.io.Fileare 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/binfolder of the project. You can figure this by printingnew File(".").getAbsolutePath().But you shouldn’t be relying on relative paths in
Fileat 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.Note that the
getServletContext()is inherited from theGenericServletclass which theHttpServletextends from, so you don’t need to provide the method yourself.