Need to get absolute path in java class file, inside a dynamic web application...
Actually i need to get path of apache webapps folder... where the webapps are deployed
e.g. /apache-root/webapps/my-deployed-app/WebContent/images/imagetosave.jpg
Need to get this in a java class file, not on jsp page or any view page...
any ideas?
Actually i need to get path of apache webapps folder... where the webapps are deployed
e.g. /apache-root/webapps/my-deployed-app/WebContent/images/imagetosave.jpg
As mentioned by many other answers, you can just use ServletContext#getRealPath()
to convert a relative web content path to an absolute disk file system path, so that you could use it further in File
or FileInputStream
. The ServletContext
is in servlets available by the inherited getServletContext()
method:
String relativeWebPath = "/images";
String absoluteDiskPath = getServletContext().getRealPath(relativeWebPath);
File file = new File(absoluteDiskPath, "imagetosave.jpg");
// ...
However, the filename "imagetosave.jpg" indicates that you're attempting to store an uploaded image by FileOutputStream
. The public webcontent folder is the wrong place to store uploaded images! They will all get lost whenever the webapp get redeployed or even when the server get restarted with a cleanup. The simple reason is that the uploaded images are not contained in the to-be-deployed WAR file at all.
You should definitely look for another location outside the webapp deploy folder as a more permanent storage of uploaded images, so that it will remain intact across multiple deployments/restarts. Best way is to prepare a fixed local disk file system folder such as /var/webapp/uploads
and provide this as some configuration setting. Finally just store the image in there.
String uploadsFolder = getItFromConfigurationFileSomehow(); // "/var/webapp/uploads"
File file = new File(uploadsFolder, "imagetosave.jpg");
// ...