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.
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 or from a JSP?
EDITED: If you're inside a Servlet object, then call getServletContext()
. If you're in JSP, use the predefined variable application
.
Here is how it works for me with no Servlet use.
Let's say I am trying to access web.xml in project/WebContent/WEB-INF/web.xml
In project property Source-tab add source folder by pointing to the parent container for WEB-INF folder (in my case WebContent )
Now let's use class loader:
InputStream inStream = class.getClass().getClassLoader().getResourceAsStream("Web-INF/web.xml")
The problem I had accessing the sqlite db file I created in my java (jersey) server had solely to due with path. Some of the docs say the jdbc connect url should look like "jdbc:sqlite://path-to-file/sample.db". I thought the double-slash was part of a htt protocol-style path and would map properly when deployed, but in actuality, it's an absolute or relative path. So, when I placed the file at the root of the WebContent folder (tomcat project), a uri like this worked "jdbc:sqlite:sample.db".
The one thing that was throwing me was that when I was stepping through the debugger, I received a message that said "opening db: ... permission denied". I thought it was a matter of file system permissions or perhaps sql user permissions. After finding out that SQLite doesn't have the concept of roles/permissions like MySQL, etc, I did eventually change the file permissions before I came to what I believe was the correct solution, but I think it was just a bad message (i.e. permission denied, instead of File not found).
Hope this helps someone.