2012-12-10 39 views
1

我在java中有一個Web應用程序項目。如果我部署項目,那麼項目有Tomcat服務器上的文件夾層次的結構如下:如何從文件夾中讀取WEB-INF文件夾外部的文件?

-conf
-image
-META-INF
-profiles
-WEB-INF

我想從文件夾「profiles」和「config」中讀取一些文件。我試過使用

Properties prop = new Properties(); 
try{ 
    prop.load(new FileInputStream("../webapps/WebApplicatioProject/profiles/file_001.properties")); 
} catch (Exception e){ 
    logger.error(e.getClass().getName()); 
} 

它沒有工作。然後我用

Properties prop = new Properties(); 
try{ 
    prop.load(getClass().getResourceAsStream("../../../../profiles/fille_001.properties")); 
} catch (Exception e){ 
    logger.error(e.getClass().getName()); 
} 

它也沒有工作。

如何從WEB-INF文件夾以外的文件夾「profiles」和「conf」中讀取文件?

+2

不要把服務器文件的WEB-INF之外,因爲用戶可以簡單地輸入WEBCONTEXT/conf目錄在瀏覽器中讀取文件。 – Stefan

回答

0

如果您確實需要,您可以對該位置進行逆向工程。在捕獲通用異常並記錄File.getPath()之前捕獲FileNotFoundException,這將輸出絕對文件名,您應該能夠看到相對路徑從哪個目錄派生而來。

1

正如斯特凡說,不要把他們趕出WEB-INF/...所以把它們放到WEB-INF /,然後以這種方式閱讀:

ResourceBundle resources = ResourceBundle.getBundle("fille_001"); 

現在,您可以訪問屬性在fille_001.properties中。

1

您可以使用ServletContext.getResource(或getResourceAsStream)使用相對於Web應用程序的路徑(包括但不限於WEB-INF下的路徑)訪問資源。

InputStream in = ctx.getResourceAsStream("/profiles/fille_001.properties"); 
if(in != null) { 
    try { 
    prop.load(in); 
    } finally { 
    in.close(); 
    } 
} 
0

您應該使用ServletContext.getResourcegetResourceAsStream在本地爲我工作,但在詹金斯失敗。

-1

您可以使用

this.getClass().getClassLoader().getResourceAsStream("../../profiles/fille_001.properties") 

基本上類加載器開始尋找資源轉化爲Web-Inf/classes文件夾中。所以通過提供相對路徑我們可以訪問web-inf文件夾之外的位置。

+0

此解決方案不起作用。 –

1

如果該文件位於WebContext文件夾下,則我們通過調用ServletContext獲取對象引用。

Properties props=new Properties(); 
    props.load(this.getServletContext().getResourceAsStream("/mesdata/"+fileName+".properties")); 

如果該文件是類路徑下使用的類加載器我們可以得到該文件的位置

Properties props=new Properties(); 
    props.load(this.getClass().getClassLoader.getResourceAsStream("/com/raj/pkg/"+fileName+".properties")); 
相關問題