Not able to load properties file in Java

可紊 提交于 2019-12-30 11:57:32

问题


I am trying to load a properties file. The properites file is in the class path of the application.

 Properties p = new Properties();
 p.load(new FileInputStream("classpath:mail.properties"));
 System.out.println(p.get("hi"));

Now I say classpath, because another file called x.properties is referred in an xml file like this

<property name="x">
    <util:properties location="classpath:x.properties" />
</property>

I placed my mail.properties in the same folder as x.properties, but my Java program is not able to find it ? Any idea what I am missing ?


回答1:


Just because some program processing that XML file likes the syntax classpath:x.properties doesn't mean that it is a universally accepted syntax in Java!

If you provide "classpath:x.properties" to a FileInputStream it will look for a file named classpath:x.properties. (Check the documentation of that particular constructor.)

Try providing the full path to that file. If the file happens to be on your class path, you could use something like

p.load(getClass().getResourceAsStream("mail.properties"));



回答2:


if mail.properties is indeed on your classpath, you will have better luck loading it via a class loader:

Properties p = new Properties();
InputStream is = getClass().getClassLoader().getResourceAsStream("mail.properties");
p.load(is);


来源:https://stackoverflow.com/questions/7596155/not-able-to-load-properties-file-in-java

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!