views:

709

answers:

3

I wrote some code to read a file in my Java Servlet class. (I'm using Netbeans on Windows along with Tomcat server). However, my servlet cannot find the file!

After much digging, I found that I had to place the file I wanted to read in Tomcat/bin folder. That's very surprising. How can I get the path to my Webapps/ folder? Let's assume my website project is called "Web1".

Essentially what I'm doing is I'm trying to read my .xsl file for converting my DOM Document to be an HTML. At first I tried placing this .xsl file everywhere (at the same level as my index.jsp, in the same directory as my servlet class file, etc...but didnt work at all)

Also, when I finished transform(), my HTML file also goes into the Tomcat/bin folder~!

+4  A: 

Can you use javax.servlet.ServletContext.getRealPath(String path)?

Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns the absolute file path on the server's filesystem would be served by a request for "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext.. The real path returned will be in a form appropriate to the computer and operating system on which the servlet container is running, including the proper path separators. This method returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).

lumpynose
the technique you suggested works...though i wonder if there's a way to just get relative path.
ShaChris23
A: 

Where are you consuming that XSL? If from your Java code place the file into src/java/resources so it will end up in the top of your classpath when the WAR is assembled /WEB-INF/classes/foo.xsl. Then you can use Class#getResource("foo.xsl") or even better if you are using DOM4J or equivalent there are ways of loading the file. Now if it is you JavaScript that performs the transformation on the client that's a different story

DroidIn.net
A: 

Something like this might be more convenient for you:

 java.net.URL url = ClassLoader.getSystemResource(file_name);
 try {
  InputStream is = url.openStream());
  //Read the file and do stuff
 } catch(IOException e) {
  System.err.println("Error: could not load the file");
 }

This will allow you to get an InputStream for a file within the classpath (in your case, something in the webapps folder). As for writing results, I'm not sure.

Dana the Sane