tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jacob Kjome <Jacob.R.Kj...@syntegra.com>
Subject RE: loading a properties file - where does it expect the file tobe?
Date Wed, 27 Sep 2000 18:01:15 GMT
Thank you!

That is exactly what I was looking for :-)


Jake

-----Original Message-----
From: Craig R. McClanahan [mailto:Craig.McClanahan@eng.sun.com]
Sent: Wednesday, September 27, 2000 12:38 PM
To: tomcat-user@jakarta.apache.org
Subject: Re: loading a properties file - where does it expect the file
tobe?


Jacob Kjome wrote:

> The following isn't a problem for me in Tomcat 3.1, but is in 3.2b5
>
> I have a servlet that uses another class that isn't a servlet which loads
a
> file with properties in it.
>
> When I run the class as an application, it works fine.
>
> However, when calling it from a servlet, it can't find the file???
>
> The location of my non-servlet class is, currently, in the same directory
> as my servlet class (and so is my properties file).
>

The problem you are having is based on the fact that you are trying to use a
filename, which is resolved by the OS as relative to the current working
directory.
When you are running in a servlet container, the current working directory
is not in
your control.

The best way to deal with stuff like this is to not use files at all.
Instead, use
Class.getResourceAsStream() as the mechanism to load your properties from
the same
place that the class file is.  Example code (assuming the properties
filename is
"myprops.properties":

    Properties props = new Properties();
    try {
        InputStream stream =
          this.getClass().getResourceAsStream("myprops.properties");
        props.load(stream);
        stream.close();
    } catch (Throwable t) {
        ... deal with exception ...
    }

The reason this is better is that it works even when the class (and the
corresponding
properties file) are packaged into a JAR file on the classpath (or installed
in
WEB-INF/lib in a web application).  In this scenario, file I/O is not going
to work
at all, because the properties are not stored in a separate file at all.
The
getResourceAsStream() method deals with all of that for you.

>
> Jake

Craig McClanahan

====================
See you at ApacheCon Europe <http://www.apachecon.com>!
Session VS01 (23-Oct 13h00-17h00):  Sun Technical Briefing
Session T06  (24-Oct 14h00-15h00):  Migrating Apache JServ
                                    Applications to Tomcat


Mime
View raw message