Ajay
Ajay

Reputation:

Property file in java

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

Upvotes: 2

Views: 2077

Answers (4)

Keaz
Keaz

Reputation: 985

let say ur class is TestClass then ur code must change to ,

InputStream input = TestClass.class.getResourceAsStream("abc.properties");
property.load(input);

Upvotes: 0

kgiannakakis
kgiannakakis

Reputation: 104168

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

Upvotes: 1

Thilo
Thilo

Reputation: 262464

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.

Upvotes: 1

skaffman
skaffman

Reputation: 403441

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.

Upvotes: 6

Related Questions