Trying to find a file to write to dynamically is not a best practice.
While some app servers will unpack a war file into a directory structure, others will not. getRealPath(String) will return null if your app is being run from a war file (as opposed to an exploded directory structure).
You're better off configuring an absolute path as a servlet init param or a context init param.
Hi Vani, File myFile = new File("..//myTest//xml//defaultXmlFiles",fileName); is not the right way to do it. You are mapping a relative path. But in this case not relative to root context of the web app but relative to tomcat root directory. You have following solutions. 1) Provide absolute path..(Hardcoding ..Bad idea) 2)Calibrate the path WRT tomcat root. (Tomcat specific Hardcoding .. Bad idea.) 3) Use ServletContext.getRealPath("/webResources/textFiles/*.txt") (Should work in all web containers.)
The difference between winner and loser is making things happen and letting things happen.
3) Use ServletContext.getRealPath("/webResources/textFiles/*.txt") (Should work in all web containers.)
This will not work in all containers. The servlet spec requires that apps be able to be run from a war file. It doesn't require that appservers unpack the war file into a directory structure on file system. When apps are run from a war file (not unpacked), getRealPath will return null.
The most dependable solution you will come up with is to use an absolute path, configured as either a servlet init param or a context init param.
Also: if this path points to a directory in your webapp and you are running the app in a packed war file, you will also run into a problem.
Another option is to use the 'tempdir' provided to each app by the container.
Joined: Apr 11, 2001
Thanks for your replies.
I don't have war files.
How would I give init param or context param to a servlet?
How would I call this servlet from java class instead of webpage?
how could this init param help to get the context path? [code] <servlet> <servlet-name>MyServlet</servlet-name> <display-name>MyServlet</display-name> <init-param> <param-name>path</param-name> <param-value>//myTestFile/xml/defaultXmlFiles</param-value> </init-param> <description>Simple text servlet</description> <servlet-class>image_gallery.MyServlet</servlet-class> </servlet> [code]
My point was that you shouldn't write apps that depend on being able to find a particular directory based on the location of the context because, depending, on how your app is run, the context may not have a physical location on the file system.