radioAe6rt

Accessing configuration-type files from a Java webapp

leave a comment »

A few people in the last few days on the Tomcat Users List
Tomcat Logo
have essentially asked: How do I read a file from disk from within my web application, and furthermore, how do I declaratively configure the name of that file so as to keep its path out of my code?

It’s a common question, and one good solution applies to any Java application, not just a web application running in a container.

Here’s a frequently used scheme: bundle the file of interest in your application’s war file, and from within your application, read its contents as a resource.

Assume the application’s context is named myapp, the file of interest is thisfile.dat, and that you can arrange through the jar-ing process/task for the file to be placed in your application’s WEB-INF/classes directory. When the application is unbundled by Tomcat, you should see the file in a directory listing

$ cd CATALINA_HOME
$ ls webapps/myapp/WEB-INF/classes/thisfile.dat
webapps/myapp/WEB-INF/classes/thisfile.dat

And while this is clearly Unix-like syntax, the same ideas apply to Windows.

What have we done so far? Strategically place the file along the application’s classpath. This is essential to the scheme: the file must be along the application’s classpath – and nowhere else. This is probably worth a close read

Class Loader HOW-TO

Futhermore, to declaratively configure your application, you’d like to put this file path in your application configuration, which keeps it hardcoded out of your code. In other words, in the application’s web.xml file.

So among other application configuration, you put this in your web.xml

 
<servlet>
   <init-param>
      <param-name>thefile</param-name>
      <param-value>/thisfile.dat</param-value>
   </init-param>
</servlet> 

Finally, somewhere in your servlet, you set about retrieving the file contents as follows:

 
String thefile = this.getInitParameter("thefile");
InputStream is = this.getClass().getResourceAsStream(thefile); 

That’s all there is to it. Of course, all of this assumes you have a method of using an InputStream to parse or process the file, but that is generally a good assumption.

Update

Tim Lucia points to this good article on the same topic. There are some useful points therein regarding other forms of loading resources that are worth knowing.

[tags]tomcat,java resource[/tags]

Written by radioae6rt

May 16, 2006 at 8:48 pm

Posted in Internet

Leave a Reply