tomcat 5.5 - 读取资源文件的问题

Vla*_*ner 8 java resources tomcat servlets

我正在使用Tomcat 5.5作为我的servlet容器.我的Web应用程序通过.jar部署,并在其WEB-INF目录下有一些资源文件(带有字符串和配置参数的文本文件).Tomcat 5.5在ubuntu linux上运行.使用文件读取器读取资源文件:
fr = new FileReader("messages.properties");

问题是有时servlet找不到资源文件,但如果我重新启动它几次就可以了,那么经过一段时间它再次停止工作.有人可以建议从servlet读取资源字符串的最佳方法是什么?或解决此问题的方法?将资源文件放在WEB-INF/classes下也无济于事.

Jam*_*hek 9

如果您尝试从Servlet感知类(例如ContextListener或其他生命周期侦听器)访问此文件,则可以使用ServletContext对象获取资源的路径.

这三个大致相当.(不要将getResourceAsStream混淆为与ClassLoader类提供的相同.它们的行为完全不同)

void myFunc(ServletContext context) {
   //returns full path. Ex: C:\tomcat\5.5\webapps\myapp\web-inf\message.properties 
   String fullCanonicalPath = context.getRealPath("/WEB-INF/message.properties");

   //Returns a URL to the file. Ex: file://c:/tomcat..../message.properties
   URL urlToFile = context.getResource("/WEB-INF/message.properties");

   //Returns an input stream. Like calling getResource().openStream();
   InputStream inputStream = context.getResourceAsStream("/WEB-INF/message.properties");
   //do something
}
Run Code Online (Sandbox Code Playgroud)


dic*_*ciu 5

我猜你的问题是你正在尝试使用相对路径来访问该文件.使用绝对路径应该有帮助(即"/home/tomcat5/properties/messages.properties").

但是,此问题的常见解决方案是使用ClassLoader的getResourceAsStream方法.将属性文件部署到"WEB-INF/classes"将使其可用于类加载器,您将能够访问属性流.

未经测试的原始代码:

Properties props = new Properties();

InputStream is =
getClass().getClassLoader().getResourceAsStream("messages.properties");

props.load(is);
Run Code Online (Sandbox Code Playgroud)