How to find the working folder of a servlet based application in order to load resources

China☆狼群 提交于 2019-11-26 12:32:22
BalusC

You could use ServletContext#getRealPath() to convert a relative web content path to an absolute disk file system path.

String relativeWebPath = "/WEB-INF/static/file1.ext";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file);
// ...

However, if your sole intent is to get an InputStream out of it, better use ServletContext#getResourceAsStream() instead as getRealPath() may return null whenever the WAR is not expanded on local disk file system (Tomcat by default does, but is configureable to not do so!):

String relativeWebPath = "/WEB-INF/static/file1.ext";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...

This is after all much more robust than the java.io.File approach.

See also:

I would prefer to use the getResourceaAsStream option to load the resource based on the parent directory.

getClass().getClassLoader().getResourceAsStream("/MY_STATIC_FOLDER/file1");

You can try this
String relativeWebPath = "WEB-INF/static/file1.ext";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!