tags:

views:

148

answers:

2

How can I check if a file exists in a war file? I know I can use

boolean doesExist = new File(myfile).exists();

but how do I use that in a java class in the war? The file.getAbsolutePath() just shows where the war file is running. I need to check if there is an image in another directory in the war that matchs the filename in the war so I can display that or a generic image if it doesn't exist.

+4  A: 

ServletContext.getResource()

From javadoc:

This method returns null if no resource is mapped to the pathname.

axtavt
+3  A: 

Below is an approach you should use only if your war is not deployed and you want to check it via some external tool.

If the war is deployed, and you have a ServletContext available, then use it instead (as shown in axtavt's answer)

A war file is a zip file, so you can read it with the java.util.zip package, Using ZipFile:

ZipFile zipFile = new ZipFile("/path/to/archive.war");
ZipEntry entry = zipFile.getEntry("yourSearchedEntry");
if (entry == null) {
   // the file is not found in the war.
}
Bozho