[英]How to check if a file exists in a war file?
如何檢查war文件中是否存在文件? 我知道我可以使用
boolean doesExist = new File(myfile).exists();
但是如何在戰爭中的java類中使用它呢? file.getAbsolutePath()只顯示war文件的運行位置。 我需要檢查戰爭中另一個目錄中是否存在與戰爭中的文件名匹配的圖像,以便我可以顯示該圖像或一般圖像(如果它不存在)。
ServletContext.getResource()
來自javadoc:
如果沒有資源映射到路徑名,則此方法返回null。
以下是一種只有在未部署戰爭並且想要通過某些外部工具進行檢查時才應使用的方法。
如果部署了war,並且你有一個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.
}
你需要使用getServletContext()。getRealPath(“/”)
File f = new File(session.getServletContext().getRealPath("/")+"/myFile.ext");
if (f.exists()) {
.......
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.