Property file in java

2019-07-18 02:57发布

问题:

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

回答1:

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.



回答2:

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.



回答3:

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



回答4:

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

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