This week's giveaway is in the Android forum.
We're giving away four copies of Android Security Essentials Live Lessons and have Godfrey Nolan on-line!
See this thread for details.
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 Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Java » JSP
Bookmark "File Creation In a webapp" Watch "File Creation In a webapp" New topic
Author

File Creation In a webapp

Simon Carroll
Greenhorn

Joined: Oct 19, 2005
Posts: 3
Hi,

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:

java.io.File f = new java.io.File("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
Sheriff

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
Greenhorn

Joined: Oct 19, 2005
Posts: 3
Your solution worked a treat, thanks very much
 
 
subject: File Creation In a webapp
 
Similar Threads
webwork beginners filepath confusion
axis simple examples error
Request Resource not available.
Tomcat 5.5 manual deployment
Class Not found Exception