我需要使用java获取Web容器路径,有什么方法可以实现吗?我需要使用 JSP 或 Servlet 来获取文件路径。
最佳答案
I need to use it using JSP or Servlet to get a file path.
那么该文件存储在 WAR 的公共(public) Web 内容中?使用ServletContext#getRealPath()
.
String relativeWebPath = "/file.jpg";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath);
InputStream input = new FileInputStream(file); // I guess this is what you want.
// ...
请注意,这仅在容器扩展 WAR 时才有效。否则最好使用ServletContext#getResourceAsStream()
如果您真正想要的是获取它的InputStream
。
String relativeWebPath = "/file.jpg";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...
另请参阅:
关于java - 如何使用java知道web容器的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6097814/