I've seen a lot of examples where people try to read properties files from WEB-INF/classes directory. I need to read an xml, I basically, need to get the fully qualified path name of the xml file, as my ancient xml parser (please don't ask), can only take a file name. So getResourceAsStream won't work for me. However, I'm having problems with the most basic step. My xml file is in the classes directory. I use getClass().getResoure() to get a handle on the xml file as a URL, and from there I was going to try and figure out the path name. However, the URL always comes back null. Any suggestions? Thanks! Jason
Hi, Jason. You are right - WEB-INF is a good place for stuff which should not be publically accessed. But I think that "classes" folder is not a good place - it could be rewritten by Servlet Container after servlets redeployment. So, create under WEB-INF some folder for your XML stuff: like "WEB-INF/xml_stuff" To get full path you can use following expression: (inside HTTP Servlet)
Thanks for the response Mikalai! I forgot to mention that this is in a normal, non servlet java class. I suppose I have the option of passing that information into the java class from the generating servlet, but just out of curiosity, do you have any more tricks up your sleeve? Is there any other way to get that information? I want to change as few classes as possible. At least you have given me some options to work with now, thanks again! Jason
Hello, I just wrote an example. In my project I also has separate class for accessing to external resourses, but this class is called from init() method of servlet and servlet pass to business method full path to XML file as argument. You can do the same. Mikalai.
Mikalai Zaikin wrote: [I][/I] While this will work for some aplications in some servlet containers, it is a risky thing to do. If your "classes" are in a jar file, your "webRoot" variable will null. Just as it will in a servlet container which reads the resources straight from a war file rather than going through the trouble of expanding the war file to a directory. In general the use of "getRealPath" is dangerous, and will get more dangerous as more servlet containers access war files in situ. My suggestion to solve your problem is one which should work in all servlet containers, and however your web app is deployed (files, war, ear etc.) Step 1. Find the servlet container "temporary directory" by reading the "javax.servlet.context.tempdir" context attribute. All compliant servlet containers must provide one for each loaded web application. Step 2. Open your XML resource file as a stream. Step 3. Copy the stream to a file in the temporary directory. Step 4. Run your XML parser on the freshly created file. Step 5. Delete the new file when you've finished with it. Here's some example (untested) code: