如何在WebContent文件夹中获取文件的真实路径?
-
03-10-2019 - |
题
我需要在WebContent目录中获取文件的真实路径,以便我使用的框架可以访问该文件。它仅将字符串文件作为属性,因此我需要在WebContent Directory中获取该文件的真实路径。
我使用弹簧框架,因此应该在春季进行解决方案。
解决方案
如果您需要在servlet中,请使用 getServletContext().getRealPath("/filepathInContext")
!
其他提示
getServletContext()。getRealPath(“”) - 如果从.war存档提供内容,则这种方式将无法工作。 getservletContext()将为null。
在这种情况下,我们可以使用另一种方法来获取真正的路径。这是获取通往属性文件的路径c:/program files/tomcat 6/webapps/myapp/web-inf/class/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");
您必须告诉Java将路径从PC更改为Java项目,因此,如果您使用春季:使用:
@Autowired
ServletContext c;
String UPLOAD_FOLDEdR=c.getRealPath("/images");
但是,如果您使用servlet,只需使用
String UPLOAD_FOLDEdR = ServletContext.getRealPath("/images");
所以这条路将是 /webapp/images/
:)
在这种情况下,我倾向于将所需的内容提取为资源(myClass.getClass()。getResourCeasStream()),将其作为文件写入临时位置,然后将此文件用于其他呼叫。
这样,我就不必费心仅在罐子中包含的内容或根据我当前使用的Web容器的位置。
将请求包括为参数。然后,弹簧调用映射方法时将传递请求对象
@RequestMapping .....
public String myMethod(HttpServletRequest request) {
String realPath = request.getRealPath("/somefile.txt");
...
您可以使用Spring Resource接口(尤其是ServletContextresource): http://static.springsource.org/spring/docs/current/javadoc-api/org/springframework/core/core/io/resource.html
此方法使用资源加载程序获取应用程序中文件的绝对路径,然后将其升至应用程序的根文件夹。无需servlet上下文!如果您在Web-Inf文件夹中有“ web.xml”,这应该有效。请注意,您可能需要考虑仅将其用于开发,因为这种类型的配置通常是从应用程序外部存储的。
public String getAppPath()
{
java.net.URL r = this.getClass().getClassLoader().getResource("web.xml");
String filePath = r.getFile();
String result = new File(new File(new File(filePath).getParent()).getParent()).getParent();
if (! filePath.contains("WEB-INF"))
{
// Assume we need to add the "WebContent" folder if using Jetty.
result = FilenameUtils.concat(result, "WebContent");
}
return result;
}
当您想在开发和生产级别中使用arff.txt时,请尝试使用它
String path=getServletContext().getRealPath("/WEB-INF/files/arff.txt");