我在以下位置的网络项目中有一个pdf文件:
" static / Downloadables / 20 / Home_insurance_booklet.pdf"
"静态"存在于WebContent中。项目的上下文根是" pas"。
在其中一个jsp中,我需要检查文件Home_insurance_booklet.pdf是否存在。我尝试过很多方法,但无法成功。以下是我使用的代码。
String filePath = request.getContextPath()+"/static/Downloadables/20/Home_insurance_booklet.pdf";
if(new File(filePath.toString()).exists()) {
------
}
通过该文件存在,条件返回false。如何检查文件是否存在w.r.t到Web项目根目录中的某个位置?
编辑: 显示的文件路径是 /pas/static/Downloadables/20/Home_insurance_booklet.pdf
答案 0 :(得分:2)
尝试以下方法:
String path = getServletContext().getRealPath("/static/Downloadables/20/Home_insurance_booklet.pdf")
File file = new File(path)
if (file.exists()) {
// Success
}
以下是getRealPath()
的API-Doc:
http://docs.oracle.com/javaee/6/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)
答案 1 :(得分:1)
使用
ServletContext context = request.getServletContext();
StringBuilder finalPathToFile = new StringBuilder(context.getRealPath("/"));
ServletContext#getRealPath()将Web内容路径(服务器磁盘文件系统上展开的WAR文件夹结构中的路径)转换为绝对磁盘文件系统路径。 / p>
"/"
代表网络内容根。
之后以这种方式附加:
finalPathToFile.append("/static/Downloadables/20/Home_insurance_booklet.pdf");
然后使用
if(new File(finalPathToFile.toString()).exists()) {
---------------------
doWhateverYouWantToDo
---------------------
}
答案 2 :(得分:0)
您必须使用基于文件系统的URL而不是相对基于Web的URL。
答案 3 :(得分:0)
检查文件是否已加载到项目中。然后在代码中首先尝试绝对路径,然后尝试相对路径。