2010-01-13 135 views
2

如何檢查文件是否存在於war文件中?我知道我可以使用如何檢查文件是否存在於war文件中?

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

但是我如何在戰爭的java類中使用它? file.getAbsolutePath()只顯示war文件的運行位置。我需要檢查戰爭中的其他目錄中是否存在與戰爭中的文件名相匹配的圖像,以便我可以顯示該圖像或通用圖像(如果它不存在)。

回答

6

ServletContext.getResource()

,通過javadoc:

如果沒有資源被映射到路徑此方法返回null。

6

下面是你應該使用的方法只有如果你的戰爭不是部署要通過一些外部工具進行檢查。

如果戰爭部署,和你有一個ServletContext可用,然後用它來代替(如圖axtavt的答案)

一個war文件是一個zip文件,這樣你就可以與java.util.zip包讀它, 使用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. 
} 
0

您需要使用getServletContext()方法getRealPath( 「/」)

File f = new File(session.getServletContext().getRealPath("/")+"/myFile.ext"); 
if (f.exists()) { 
....... 
}