如何查找基于 servlet 的应用程序的工作文件夹以加载资源
我编写了一个 Java servlet,希望将其安装在不同服务器上的多个 Tomcat 实例上。 servlet 使用一些静态文件,这些静态文件与 WEB-INF 下的 war 文件一起打包。这是典型安装中的目录结构:
- tomcat
-- webapps
--- myapp
---- index.html
---- WEB-INF
----- web.xml
----- classes
------ src
------- .....
----- MY_STATIC_FOLDER
------ file1
------ file2
------ file3
如何知道 MY_STATIC_FOLDER 的绝对路径,以便我可以读取静态文件?
我不能依赖“当前文件夹”(我在新文件(“.”)中得到的内容),因为它取决于 Tomcat 服务器的启动位置,这在每次安装中都是不同的!
I write a Java servlet that I want to install on many instances of Tomcat on different servers. The servlet uses some static files that are packed with the war file under WEB-INF. This is the directory structure in a typical installation:
- tomcat
-- webapps
--- myapp
---- index.html
---- WEB-INF
----- web.xml
----- classes
------ src
------- .....
----- MY_STATIC_FOLDER
------ file1
------ file2
------ file3
How can I know the absolute path of MY_STATIC_FOLDER, so that I can read the static files?
I cannot rely on the "current folder" (what I get in a new File(".")) because it depends on where the Tomcat server was started from, which is different in every installation!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用
ServletContext#getRealPath()
将相对 Web 内容路径转换为绝对磁盘文件系统路径。但是,如果您的唯一目的是从中获取
InputStream
,最好使用ServletContext#getResourceAsStream()
因为getRealPath()
可能会返回每当 WAR 未扩展到本地磁盘文件系统而是扩展到内存和/或虚拟磁盘时,null
:这比
java.io.File
方法更加健壮。此外,使用 getRealPath() 被认为是不好的做法。另请参阅:
You could use
ServletContext#getRealPath()
to convert a relative web content path to an absolute disk file system path.However, if your sole intent is to get an
InputStream
out of it, better useServletContext#getResourceAsStream()
instead becausegetRealPath()
may returnnull
whenever the WAR is not expanded into local disk file system but instead into memory and/or a virtual disk:This is much more robust than the
java.io.File
approach. Moreover, usinggetRealPath()
is considered bad practice.See also:
你可以试试这个
<代码>
StringrelativeWebPath = "WEB-INF/static/file1.ext";
InputStream 输入 = getServletContext().getResourceAsStream(relativeWebPath);
You can try this
String relativeWebPath = "WEB-INF/static/file1.ext";
InputStream input = getServletContext().getResourceAsStream(relativeWebPath);
我更愿意使用 getResourceaAsStream 选项根据父目录加载资源。
I would prefer to use the getResourceaAsStream option to load the resource based on the parent directory.