new*_*bie 10 java spring realpath webcontent
我需要在我的WebContent目录中获取文件的真实路径,以便我使用的框架可以访问该文件.它只将String文件作为属性,因此我需要在WebContent目录中获取该文件的真实路径.
我使用Spring Framework,因此应该可以在Spring中进行解决方案.
Shy*_*yam 13
如果你需要在servlet中使用它,那么使用getServletContext().getRealPath("/filepathInContext")
!
A K*_*nin 12
getServletContext().getRealPath("") - 如果从.war存档中提供内容,则这种方式不起作用.getServletContext()将为null.
在这种情况下,我们可以使用另一种方式来获得真实路径.这是获取属性文件C:/ Program Files/Tomcat 6/webapps/myapp/WEB-INF/classes/somefile.properties的路径的示例:
// URL returned "/C:/Program%20Files/Tomcat%206.0/webapps/myapp/WEB-INF/classes/"
URL r = this.getClass().getResource("/");
// path decoded "/C:/Program Files/Tomcat 6.0/webapps/myapp/WEB-INF/classes/"
String decoded = URLDecoder.decode(r.getFile(), "UTF-8");
if (decoded.startsWith("/")) {
// path "C:/Program Files/Tomcat 6.0/webapps/myapp/WEB-INF/classes/"
decoded = decoded.replaceFirst("/", "");
}
File f = new File(decoded, "somefile.properties");
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
59487 次 |
最近记录: |