Win a copy of Programmer's Guide to Java SE 8 Oracle Certified Associate (OCA) this week in the OCAJP forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

File Creation In a webapp

 
Simon Carroll
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13411
Firefox Browser Redhat VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Simon Carroll
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Your solution worked a treat, thanks very much
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic