【问题标题】:Properties File is not accessible from Java Class无法从 Java 类访问属性文件
【发布时间】:2015-04-26 11:30:29
【问题描述】:

我正在使用 servlet、jsp 和 java 类构建 Web 应用程序。

这里是java结构

我想访问system.properties 文件,因为该文件正在存储项目配置。

我所做的是使用此 java 代码使用 FileInputStream 获取文件

/* 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 文件夹中时。

【问题讨论】:

  • system.properties 放入WEB-INF/classes 并在getResourceAsStream("/system.properties") 中添加/
  • 试试InputStream inputStream = class.getClass().getClassLoader().getResourceAsStream("WEB-INF/system.properties");,而不是你的inputStream
  • 如果属性文件不可访问你会得到一个异常prop.load()你能在getProperty之后记录host的值吗?

标签: java jsp servlets properties


【解决方案1】:

我只能想到一件事,那就是您没有将属性文件放在类路径中,以检查是否将一些日志放入您的 if 语句中,如下所示:

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

你可以看到你的输入流是空的并且没有任何东西被加载到你的prop,我可以看到你正在使用eclipse所以使用this answer

【讨论】:

  • 但是他的 log4j 属性在同一个位置,并且似乎可以正常使用?
  • @RaGe 我们无法知道该 log4j 文件是否被拾取。要将文件作为资源加载,它必须位于类路径上,并且 OP 不太可能更改容器,因此它包含非标准目录。正如所问的,这几乎可以肯定是答案。
  • @Rage 我在这里发现的是 java 项目无法从指定的文件夹加载属性文件。我尝试创建新的资源文件夹然后从中访问,但仍然没有运气,无法加载属性文件。
  • @DaveNewton 我尝试将 else 语句放入 inputStream != if 函数中。但似乎该文件没有填充尽管我已将 system.properties 更改为另一个资源文件夹。
猜你喜欢
  • 1970-01-01
  • 2012-09-29
  • 1970-01-01
  • 1970-01-01
  • 2015-11-21
  • 1970-01-01
  • 2017-05-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多