我需要获取WebContent目录下的文件的真实路径,以便我使用的框架可以访问该文件。它只使用字符串文件作为属性,因此我需要获取WebContent目录中此文件的真实路径。
我使用Spring框架,因此解决方案应该可以在Spring中实现。
我需要获取WebContent目录下的文件的真实路径,以便我使用的框架可以访问该文件。它只使用字符串文件作为属性,因此我需要获取WebContent目录中此文件的真实路径。
我使用Spring框架,因此解决方案应该可以在Spring中实现。
getServletContext().getRealPath("") - 如果内容来自.war文件,这种方法将不起作用。 getServletContext() 将为空。
在这种情况下,我们可以使用另一种方法来获取真实路径。这是获取到属性文件路径的示例 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");
getServletContext().getRealPath("/filepathInContext")
!您需要告诉Java将路径从您的电脑更改为您的Java项目,因此如果您使用Spring,请使用:
@Autowired
ServletContext c;
String UPLOAD_FOLDEdR=c.getRealPath("/images");
String UPLOAD_FOLDEdR = ServletContext.getRealPath("/images");
/webapp/images/
:)@RequestMapping .....
public String myMethod(HttpServletRequest request) {
String realPath = request.getRealPath("/somefile.txt");
...
这种方法使用资源加载器获取应用程序中文件的绝对路径,然后向上移动几个文件夹到应用程序的根文件夹。无需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;
}
我的解决方案是: ..../webapps/mydir/ (..../webapps/ROOT/../mydir/)
String dir = request.getSession().getServletContext().getRealPath("/")+"/../mydir";
Files.createDirectories(Paths.get(dir));
如果您想在开发和生产环境中使用arff.txt,可以尝试使用这个方法。
String path=getServletContext().getRealPath("/WEB-INF/files/arff.txt");