Search code examples
javaservletsfilenotfoundexceptionwebcontext

Java - load file from web context


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

Solution

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

    String path = req.getServletContext().getRealPath("/images/default.png");
    File fi = new File(path);