在java中读取.properties文件 [英] Reading .properties file in java

查看:179
本文介绍了在java中读取.properties文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have created a properties file in the location conf/Config.properties. The folder is under the project's root folder in Eclipse. I also added this to the .classpath.

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

I am reading the data from this file using the code:

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文件中读取数据?

How do I read the data from the .properties file ?

推荐答案

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

getClass().getResourceAsStream("conf/Config.properties"); tries to load the resource from a path that is relative to your class location.

使用:


  • getClass()。 getResourceAsStream(/ conf / Config.properties); (注意前导 / 这是绝对路径)或

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

  • getClass().getResourceAsStream("/conf/Config.properties"); (note the leading / this is an absolute path) or
  • getClass().getClassLoader().getResourceAsStream("conf/Config.properties"); (Note here you are using absolute path but no leading / is required)

编辑:我对你的目录结构和类路径感到困惑。根据您的评论我现在明白您的文件夹结构是:

I am confused of what your directory structure and your classpath are. By your comment I understand now that your folder structure is:

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

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

You are saying that you have added conf to your classpath. So I understand that you have two source folders in Eclipse. If this is the case then both src and conf are your root package and you should change the above commands like below:


  • getClass()。getResourceAsStream(/ Config.properties);

  • getClass()。getClassLoader()。getResourceAsStream(Config.properties);

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

这篇关于在java中读取.properties文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆