在java中读取.properties文件

新手上路,请多包涵

我在 conf/Config.properties 位置创建了一个属性文件。该文件夹位于 Eclipse 中项目的根文件夹下。我还将其添加到 .classpath 中。

我正在使用代码从该文件中读取数据:

 InputStream in = getClass().getResourceAsStream("conf/Config.properties");
Properties properties = new Properties();
properties.load(in);
String fromEmail = properties.getProperty("emailID");
System.out.println("from email is " + fromEmail);
String fromEmailPass = properties.getProperty("emailPass");
String host = properties.getProperty("host");

这给出了错误:

 java.lang.NullPointerException
    at java.util.Properties$LineReader.readLine(Properties.java:418)
    at java.util.Properties.load0(Properties.java:337)
    at java.util.Properties.load(Properties.java:325)
    at com.sendum.integration.activities.notifications.ActivityImplSendActivationEmail.activateEmail(ActivityImplSendActivationEmail.java:23)

如何从 .properties 文件中读取数据?

原文由 Ashish Agarwal 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 484
2 个回答

getClass().getResourceAsStream("conf/Config.properties"); 尝试从相对于您的类位置的路径加载资源。

要么使用:

  • getClass().getResourceAsStream("/conf/Config.properties"); (注意前导 / 这是绝对路径)或
  • getClass().getClassLoader().getResourceAsStream("conf/Config.properties"); (注意这里你使用的是绝对路径但没有前导 / 是必需的)

编辑: 我对您的目录结构和类路径感到困惑。通过您的评论,我现在了解到您的文件夹结构是:

 <Project folder>
   - src/
       // .java files
   - conf/
       Config.properties

您是说您已将 conf 添加到类路径中。所以我知道你在 Eclipse 中有 _两个源文件夹_。如果是这种情况,那么 srcconf 都是你的根包,你应该像下面这样更改上面的命令:

  • getClass().getResourceAsStream("/Config.properties");
  • getClass().getClassLoader().getResourceAsStream("Config.properties");

原文由 c.s. 发布,翻译遵循 CC BY-SA 3.0 许可协议

似乎 getClass().getResourceAsStream("conf/Config.properties"); 返回空值。这意味着目前它没有找到该文件。

尝试使用 getReasourceAsStream("./conf/Config.properties") 。这是相对路径,因为它从当前目录开始,然后找到 conf/Config.properties 或者 尝试使用绝对路径, getReasourceAsStream("/Users/user/filepath/conf/Config.properties")

在此处 查看类似的帖子。

原文由 user2638922 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题