tags:

views:

1249

answers:

2

I have a web archive with a file placed in the WEB-INF directory.

How do I load that file in a java class?

I know I can put it in the classes directory and load it from there. It would just be put it in WEB-INF.

+8  A: 

use the getResourceAsStream() method on the ServletContext object, e.g.

servletContext.getResourceAsStream("/WEB-INF/myfile");

How you get a reference to the ServletContext depends on your application... do you want to do it from a Servlet, from a JSP?

If you're inside a Servlet object, then call getServletConfig().getServletContext(). If you're in JSP, I think you can just refer to the servletContext variable, it's automatically there.

skaffman
If you are inside Servlet, you can directly use getServletContext(). :)
Adeel Ansari
Ah yes, good point.
skaffman
You can also reach to the servletContext from request->session->servletContext. In case, all you have is a request object.
Adeel Ansari
A: 

Your classes directory is the default home directory of the application, and the first place it looks for files. I haven't touched this stuff for a while, but I think you can either include ".." in the application's classpath argument, or just access the file as "../myfile".

Yuval
I think this makes for a solution, but seems rather hacked. The accepted answer should solve the problem far better.
Urs Reupke