Reputation: 352
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();
Upvotes: 0
Views: 513
Reputation: 352
Rather than getContextPath(), I needed to use getRealPath():
String path = req.getServletContext().getRealPath("/images/default.png");
File fi = new File(path);
Upvotes: 0
Reputation: 16428
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");`
Upvotes: 4