简体   繁体   中英

Access Properties File in a Maven Project

I have a java file inside src/test/java/com/pp/utils. I need to access a properties file example.properties that is inside src/test/resources from this Java file.

I tried it with :

Properties prop = new Properties();
InputStream input = null;

try {

    input = new FileInputStream("example.properties");

// load a properties file
    prop.load(input);

// get the property value and print it out
    System.out.println(prop.getProperty("key1"));

} catch (IOException ex) {
    ex.printStackTrace();
} finally {
    if (input != null) {
        try {
            input.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This gives a FileNotFound Exception. What should be the path? Or where else can I place the properties file so that it gets picked up?

try

InputStream inputStream = getClass().getResourceAsStream("/example.properties");

For clarity this assumes you properties file is in /src/test/resources, that is the root of the classpath, hence the /example.properties.

 InputStream  addrStream = <current-class>.class.getResourceAsStream("example.properties");

            prop .load(addrStream);

if my class name is PropertyUtil

InputStream  addrStream = PropertyUtil.class.getResourceAsStream("example.properties");

                prop .load(addrStream);

or

 InputStream  addrStream = getClass().getResourceAsStream("example.properties");

                    prop .load(addrStream);

use above first code if you are using properties code in main method .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM