Java/Tomcat:ServletContext& getResourceAsStream问题 [英] Java/Tomcat: ServletContext & getResourceAsStream Problems
问题描述
我正在尝试从Tomcat Web应用程序访问conf文件(位于WEB-INF文件夹中).目前,我已将该文件的位置硬编码为String
.但是,当tomcat/webapps文件夹与我的硬编码String
所指示的位置不同时,这将不起作用.我一直在网上寻找,似乎正在使用getResourceAsStream ()
方法,但我很难将其投入使用.调用getServletContext ()
方法时,我的应用程序不喜欢它.谁能帮我吗?
I am trying to access a conf file (located in the WEB-INF folder) from a Tomcat web app. At the moment, I have the location of the file hard coded as a String
. However, this does not work when the tomcat/webapps folder is in a different location than my hard coded String
indicates. I've looked online and it seems like using the getResourceAsStream ()
method is what I'm looking for, but I'm having a hard time getting it to work. My application is not liking it when I call the getServletContext ()
method. Can anyone help me?
相关的代码块
BufferedReader myReader = new BufferedReader (new InputStreamReader (getServletContext ().getResourceAsStream ("/WEB-INF/conf.txt")));
推荐答案
为解决此问题,我在WEB-INF下创建了两个文件夹(path/to/app/WEB-INF/classes/mypackage/),然后将文件放入在此文件夹中.然后,从我的POJO中调用this.getClass.getResourceAsStream ("<filename>")
打开流.为了仅获取一个字符串,它是文件的完整绝对路径名,我做了this.getClass.getResource ("<filename>").toString ().substring (5)
.
To solve this problem I created two folders under WEB-INF (path/to/app/WEB-INF/classes/mypackage/) and then put my files in this folder. Then, from my POJO I called this.getClass.getResourceAsStream ("<filename>")
to open up a stream. To just get a String that was the complete absolute path name of a file I did this.getClass.getResource ("<filename>").toString ().substring (5)
.
这篇关于Java/Tomcat:ServletContext& getResourceAsStream问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!