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

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "File Creation In a webapp" Watch "File Creation In a webapp" New topic

File Creation In a webapp

Simon Carroll

Joined: Oct 19, 2005
Posts: 3

I am trying to write an web application which will allow a user to update images being displayed on their web pages. I have written a JSP which allows the user to upload a file of their choice.

Currently all my images are stored in an images folder inside the webapp. I was wanting to upload my images to the same folder, however, when I attempt to create a new file within the JSP it tries to create a file with the following path:

C:\Program Files\Apache Software Foundation\Tomcat 5.5\images\Creek.jpg

In reality I would like the file to be created in the following folder:

C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\UpdateApplication\images

But given that I may deploy this on different environments I do not want to hard code any path settings. Is there any way I can create the file using a relative path?

The code I am using at the moment is: f = new"images/"+fileName);

which sits in a jsp in the folliowing directory:

C:\Program Files\Apache Software Foundation\Tomcat 5.5\webapps\UpdateApplication\jsp

Any help would be greatly appreciated.
Ben Souther

Joined: Dec 11, 2004
Posts: 13410

You don't want to use a relative path when working with server side Java.
You can never count on knowing what the current working directory is.

The ServletContext.getRealPath method will get you the full file system path of the resource specified . Using getRealPath("/") will get you the full path to the root of your web application.

Note: If your application is ever deployed as a packed war file, getRealPath will return null. This means using it makes your app less portable BUT, if your app needs to be able to write files to the webapp directory structure, it will won't function properly from a packed war file anyway.

Java API J2EE API Servlet Spec JSP Spec How to ask a question... Simple Servlet Examples jsonf
Simon Carroll

Joined: Oct 19, 2005
Posts: 3
Your solution worked a treat, thanks very much
I agree. Here's the link:
subject: File Creation In a webapp
It's not a secret anymore!