views:

646

answers:

3

Hi,

I want read property file in my java class.

for this i have written:

try {
            Properties property = new Properties();
            property .load(new FileInputStream("abc.properties"));
            String string = property.getProperty("userName");
        } catch (Exception e) {
            e.printStackTrace();
        }

i have placed my abc.properties file in same package where my java class resides. But i am getting FileNotFound exception.

Please let me know how to give path of property file.

Thanks and Regards

+5  A: 

The FileInputStream will look for the file in your program's "working directory", not in the same package as your class.

You need to use getClass().getResourceAsStream("abc.properties") to load your properties file from the same package.

skaffman
Surely that only works if abc.properties is actually in the default package? You need to request "my/package/abc.properties"
oxbow_lakes
No, it works. The path is relative to the class.
Thilo
Nope, it will bve loaded relative to the Class which is represented by getClass().
skaffman
thanks....getClass().getResourceAsStream("abc.properties") is working... but what will be path if i move my property file to WEB-INF ?
To load from WEB-INF, you need to use getResourceAsStream() from the ServletContext object.
skaffman
A: 

If the properties files is next to your class file, you should not use FileInputStream, but Class.getResourceAsStream.

 property.load(getClass().getResourceAsStream("abc.properties"));

This will even work when you package everything up as a jar file.

Thilo
A: 

You are better off using ClassLoader.getResourceAsStream. See this article.

kgiannakakis