Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JSP - Checking if a file exists.

Status
Not open for further replies.

croyce

Programmer
Mar 4, 2006
4
GB
I am writing a web page, where I would like to check if an image exists on the server or not. ie..

Code:
if(imageExists(image1.gif))
{
   <img src='image1.gif'/>
}
else
{
   //Do nothing
}

Something like above.

I've tried...
Code:
File file1 = new file(image1.gif);
if(file1.exists()) do this;

but it always returns false, even when the image exists. ??

Any ideas?
 
When you say :

File f = new File("image.gif");

You are saying "create a file object where the file is located in my current working directory".
Now, if you started Tomcat from TOMCAT_HOME/bin - then that directory would be your current working directory.

If you started tomcat from "/home/user" then that would be the current working directory ... .and I'm guessing that neither of those directories is actually where your file is.

So the question is .... where is your file ?

--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Funny you should mention that, i've just tried this.. Still no joy.

Code:
String strPicUrl = "../images/07News/news" + id + "image1Thumb.jpg'"; 

File theFile = new File(application.getRealPath(strPicUrl));
													out.print("File Exists: " + theFile.exists() + "<br>");

The file is in my
the jsp file is being run from (hence the ../ )
 
Code:
ServletContext app = getServletContext();

String path = app.getRealPath("");

File theFile = new File(path + "/images/07News/news/" + "news4image1.jpg");

out.print("File Exists: " + theFile.exists() + "<br>");

I've got to be close?

Cheers

 
String path = app.getRealPath("/");

Note the slash. That will return the base directory of your webapp - eg : TOMCAT_HOME/webapps/yourWebapp

Then build up the file path from that ...


--------------------------------------------------
Free Java/J2EE Database Connection Pooling Software
 
Code:
ServletContext app = getServletContext();
String path1 = app.getRealPath("images/07News/news" + id + "image1Thumb.jpg");
File theImage1 = new File(path1);

String imageURL1 = "/images/noImage.gif";

if(theImage1.exists())
{
	imageURL1 = "../images/07News/news" + id + "image1Thumb.jpg";
}

Works perfectly, just posting an answer incase anyone else reads this thread. Coz that's the kinda guy I am lol.

Cheers for the help people.

Chris
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top