2015-04-26 40 views
2

我正在使用servlet,jsp和java類構建Web應用程序。屬性文件無法從Java類訪問

。由此java的結構

project structure

我想作爲文件存儲項目配置訪問system.properties文件。

我做什麼用FileInputStream使用這個Java代碼

/* generate the properties file objects */ 
Properties prop = new Properties(); 

/* generate IO to read from properties file */ 
InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("system.properties"); 
if (inputStream != null) { 
/* load the properties file */ 
    prop.load(inputStream); 

的把所有的變量從文件轉換成目標越來越文件

host = prop.getProperty("host");

但它顯示錯誤nullpointerexception我知道屬性文件中的參數未加載。

Apr 26, 2015 7:21:14 PM org.apache.catalina.core.StandardWrapperValve invoke 
SEVERE: Servlet.service() for servlet [com.domain.servlet.TotalErrorSummaryServlet] in context with path [/MonitoringDashboard] threw exception 
java.lang.NullPointerException 

任何建議編輯system.properties文件的加載程序?當我把文件放在WEB-INF文件夾中時。

+0

把'system.properties'放入'WEB-INF/classes'中,並在' getResourceAsStream(「/ system.properties」)' – morgano

+0

嘗試'InputStream inputStream = class.getClass()。getC lassLoader()。getResourceAsStream(「WEB-INF/system.properties」);'而不是你的'inputStream'。 –

+0

如果屬性文件不可訪問,那麼當您執行'prop.load()'時,您會在getProperty之後記錄主機的值嗎? – RaGe

回答

1

我能想到的一兩件事,那就是你沒有把你的屬性在類路徑文件,檢查把一些日誌您if語句中象下面這樣:

if (inputStream != null) { 
    //some logs here 
    prop.load(inputStream); 
} 
else { 
    //and some logs here 
} 

你可以看到,你的輸入流是空的,沒有東西會加載到你的prop,並且我可以看到你正在使用eclipse所以使用this answer

+0

但他的log4j屬性是在相同的位置,似乎被拾起罰款? – RaGe

+0

@RaGe我們無法知道該log4j文件是否正在拾取。要將文件加載爲資源,它必須位於類路徑中,並且OP不太可能更改了容器,因此它包含非標準目錄。如問,這幾乎肯定是答案。 –

+0

@Rage我在這裏發現的是java項目無法從指定的文件夾加載屬性文件。我試圖創建新的資源文件夾,然後從那裏訪問,但仍然沒有運氣,屬性文件無法加載。 – randytan