0

I can't figure out why fi.exists() returns false here. I can browse to the file via the browser at contextPath+"/images/default.png

String contextPath = req.getContextPath();
File fi = new File(contextPath+"/images/default.png");
exists = fi.exists();
mrcrag
  • 310
  • 3
  • 16

2 Answers2

4

I think you missunderstood what the context path is.

If you application is deployed on yourdomain.com/app, the context path will be /app.

It is used to tell the client where to look for resources.

When you do contextPath+"/images/default.png", you the path would be dependent of the deployment path (in this case it would be the file /app/images/default.png).

If you want the file next to the installation of your application server, you can use "images/default.png".

If you want to access resource files, you may want to try Thread.currentThread().getContextClassLoader().getResource("images/default.png") instead of files.

If you want to check if a context related resource exist, you can do it as stated here:

boolean exists=req.getServletContext().getResource("images/default.png")!=null;`

or

String path=req.getServletContext().getRealPath("images/default.png");`
dan1st
  • 12,568
  • 8
  • 34
  • 67
  • Hmm, I'm not sure what you mean by 'next to the installation of your application server'. The image is not a resource, it's in the web context: `mydomain/app/images/default.png`. I tried your suggestion but still get file not found: `File fi = new File("images/default.png")` – mrcrag May 19 '21 at 15:33
  • Oh, this is what you meant. The things in the context aren't necessarily files. I have updated my answer. – dan1st May 19 '21 at 15:35
  • I had to use `getRealPath`: `String path = req.getServletContext().getRealPath("/images/default.png")` File fi = new File(path); This doesn't compile: boolean exists=req.getServletContext().getResource("images/default.png"); – mrcrag May 19 '21 at 16:00
0

Rather than getContextPath(), I needed to use getRealPath():

String path = req.getServletContext().getRealPath("/images/default.png");
File fi = new File(path);
mrcrag
  • 310
  • 3
  • 16