如何在WebContent文件夹中获取文件的真实路径?

我需要在我的WebContent目录中获取文件的真实路径,以便我使用的框架可以访问该文件。 它只将String文件作为属性,因此我需要在WebContent目录中获取此文件的真实路径。

我使用Spring Framework,因此应该可以在Spring中进行解决方案。

如果你需要在servlet中使用它,那么使用getServletContext().getRealPath("/filepathInContext")

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

你必须告诉java改变你的电脑到java项目的路径,所以如果你使用spring:

 @Autowired ServletContext c; String UPLOAD_FOLDEdR=c.getRealPath("/images"); 

但是如果你使用servlet就可以使用

 String UPLOAD_FOLDEdR = ServletContext.getRealPath("/images"); 

所以路径将是/webapp/images/ 🙂

在这些情况下,我倾向于提取我需要的内容作为资源(MyClass.getClass()。getResourceAsStream()),将其作为文件写入临时位置,并将此文件用于其他调用。

这样我就不必担心只包含在jar中的内容或位于某处的内容,具体取决于我目前正在使用的Web容器。

将请求作为参数包含在内。 然后Spring在调用映射方法时传递请求对象

 @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/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");