我在 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 许可协议
getClass().getResourceAsStream("conf/Config.properties");
尝试从相对于您的类位置的路径加载资源。要么使用:
getClass().getResourceAsStream("/conf/Config.properties");
(注意前导/
这是绝对路径)或getClass().getClassLoader().getResourceAsStream("conf/Config.properties");
(注意这里你使用的是绝对路径但没有前导/
是必需的)编辑: 我对您的目录结构和类路径感到困惑。通过您的评论,我现在了解到您的文件夹结构是:
您是说您已将
conf
添加到类路径中。所以我知道你在 Eclipse 中有 _两个源文件夹_。如果是这种情况,那么src
和conf
都是你的根包,你应该像下面这样更改上面的命令:getClass().getResourceAsStream("/Config.properties");
或getClass().getClassLoader().getResourceAsStream("Config.properties");