Java - load file from web context

401 Views Asked by At

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();
2

There are 2 best solutions below

0
mrcrag On BEST ANSWER

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

String path = req.getServletContext().getRealPath("/images/default.png");
File fi = new File(path);
3
dan1st might be happy again On

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");`