This is driving me bonkers. I’m writing a web app in Java and all I want to do is verify the existence of an image that’s saved to an /images folder right under the web root.
The 1,000,000 google searches I did seemed to indicate that the File.exists(path) method is the way to go. But for obvious reasons, I don’t want to hard code the path.
Physically, the test image file I’m working with exists on my D-drive at, let’s say, D:\documents\images\myimage.jpg. GlassFish is my local server and I don’t think my image files are replicated to a “GlassFish folder” when my app is deployed, so I think the only physical copy is the one on the D: drive.
The only way I can get:
boolean fileExists = new File(somePath).exists();
to return TRUE is using the string “D:\documents\images\myimage.jpg”. What I was after is a test like exists() that maybe uses a URL that I could couple with some other method or parameter that references the site root and I could build the rest of the URL relative to that.
Any help is much appreciated.
Since documents is the web root, you should be able to use the ServletContext.getRealPath(String) method.
http://download.oracle.com/javaee/5/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)