Java/Tomcat: ServletContext & getResourceAsStream Problems

Dan Forbes picture Dan Forbes · Aug 22, 2012 · Viewed 10.1k times · Source

I am trying to access a conf file (located in the WEB-INF folder) from a Tomcat web app. At the moment, I have the location of the file hard coded as a String. However, this does not work when the tomcat/webapps folder is in a different location than my hard coded String indicates. I've looked online and it seems like using the getResourceAsStream () method is what I'm looking for, but I'm having a hard time getting it to work. My application is not liking it when I call the getServletContext () method. Can anyone help me?

EDIT: The relevant block of code

BufferedReader myReader = new BufferedReader (new InputStreamReader (getServletContext ().getResourceAsStream ("/WEB-INF/conf.txt")));

Answer

Dan Forbes picture Dan Forbes · Aug 27, 2012

To solve this problem I created two folders under WEB-INF (path/to/app/WEB-INF/classes/mypackage/) and then put my files in this folder. Then, from my POJO I called this.getClass.getResourceAsStream ("<filename>") to open up a stream. To just get a String that was the complete absolute path name of a file I did this.getClass.getResource ("<filename>").toString ().substring (5).