tomcat-users mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Craig R. McClanahan" <Craig.McClana...@eng.sun.com>
Subject Re: Current the context from a servlet - to open a file?
Date Wed, 13 Dec 2000 22:07:34 GMT
Jeff Taylor wrote:

> When running a servlet (located in webapps/myapp/WEB-INF/classes) I'd
> like to open a ascii file (located in webapps/myapp).  What's the best
> way of obtaining the current Context -- so as not to hardcode it in?  Is
> there an appropriate class/method to call?  Thanks in advance!
>

To read file "foo.txt" from the document root, try this:

    InputStream is =
      getServletContext().getResourceAsStream("/foo.txt");

If you want to read it as characters, you can wrap an InputStreamReader around
it:

    InputStreamReader isr = new InputStreamReader(is);

This works no matter what directory your webapp runs in.  As an added bonus, it
will also work in servlet containers that don't store your webapp as a directory
at all (for example, if it runs the app directly out of a WAR file).

>
> Jeff

Craig McClanahan



Mime
View raw message