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


Reply via email to