Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

tomcat 5.5 - problem with reading resource files

I'm using Tomcat 5.5 as my servlet container. My web application deploys via .jar and has some resource files (textual files with strings and configuration parameters) located under its WEB-INF directory. Tomcat 5.5 runs on ubuntu linux. The resource file is read with a file reader:
fr = new FileReader("messages.properties");

The problem is that sometimes the servlet can't find the resource file, but if i restart it a couple of times it works, then again after some time it stops working. Can someone suggest what's the best way of reading resource strings from a servlet? Or a workaround for this problem? Putting the resource files under WEB-INF/classes doesn't help either.

like image 535
Vladimir Prenner Avatar asked Nov 18 '08 11:11

Vladimir Prenner


1 Answers

If you are trying to access this file from a Servlet-aware class, such as a ContextListener or other lifecycle listener, you can use the ServletContext object to get the path to a resource.

These three are roughly equivalent. (Don't confuse getResourceAsStream as the same as the one provided by the ClassLoader class. They behave very differently)

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
}
like image 199
James Schek Avatar answered Oct 03 '22 11:10

James Schek