如何使用Java知道web容器的路径? [英] how to know the path of the webcontainer using java?
本文介绍了如何使用Java知道web容器的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要使用java获取Web容器路径,对此有什么方法吗?我需要通过JSP或Servlet使用它来获取文件路径.
I need to get the web container path using java, is there any method for that? I need to use it using JSP or Servlet to get a file path.
推荐答案
我需要通过JSP或Servlet使用它来获取文件路径.
那么该文件存储在WAR的公共Web内容中吗?使用 ServletContext#getRealPath()
.
So the file is stored in the public webcontent of the WAR? Use 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
.
Note that this only works when the WAR is expanded by the container. Otherwise better use ServletContext#getResourceAsStream()
if all you really want is to get an InputStream
of it.
String relativeWebPath = "/file.jpg";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
// ...
另请参见:
- getResourceAsStream()vs FileInputStream
- getResourceAsStream() vs FileInputStream
See also:
这篇关于如何使用Java知道web容器的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文