简体   繁体   中英

The getProperty is returning null even after loading the property file in Java

What is wrong in the below code. Everything seems correct and no exceptions when executing. I have double verified that the test property value is there in config.properties file.

@BeforeClass
public void propertyLoading() {
    System.out.println("in beforeclass");

    prop = new Properties();
    ClassLoader classLoader = ClassLoader.getSystemClassLoader();
    try {
        System.out.println("path : "+classLoader.getResource("config.properties").getFile().toString());
        input = new FileInputStream(new File(classLoader.getResource("config.properties").getFile()));
        prop.load(input);
    } 
    catch (Exception e) {
        e.printStackTrace();
    }

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

    System.out.println("test       : "+System.getProperty("test"));
}

config.properties file contents below;

test=aaaa

Because you are using the System properties, this is not the same as runtime properties that you are trying to use

System.getProperty

while you should be calling your Properties object that you created a few lines above

prop.getProperty("test")

If you want to read your properties from System.getProperty() call

System.setProperties(prop);

after reading your properties from file

(On the sideline, use try with resources when possible https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html )

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