File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Servlets and the fly likes Save a file on the application root Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Save a file on the application root" Watch "Save a file on the application root" New topic

Save a file on the application root

Clarke Kent

Joined: Dec 19, 2005
Posts: 14

My servlet needs to save a file in the root directory of my application.

When I opened a file using the line:

This line is inside a servlet of my application. Tt doesnt get saved on the root directory of my application. Is this supposed to work?
Or do i have to explicitly get the web application root and append the filename to have the file saved on the root directory?
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

"/file.txt" would mean the root of your file system to the FileWriter class.

One thing to keep in mind is that J2EE apps aren't always run from an exploded file system. Some containers will run them right from the packed war file.
In this case there is no "root" of your web application.

That being said, the way to find the root of your web app (if there is one) would be to use ServletContext.getRealPath("/").

If your app has been deployed as a war file, getRealPath will return null.
java.lang.String)" target="_blank" rel="nofollow">

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
I agree. Here's the link:
subject: Save a file on the application root
Similar Threads
Handling menu events
Creating a new file using PrintWriter.
Saving file at server
I/O operation in jsp
Writing file from Unix to a Windows File Server