2015-04-26 41 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