Using properties file in Java: copy key value and assign it to another key

Viewed 48

is it possible to achieve below scenario using properties file in Java. Thanks a lot for any feedback.

Assume I have a settings.properties file which includes,

my.name=${name}
his.name=hisNameIs${name}

In my code,

InputStream input = new FileInputStream("path/settings.properties");
Properties prop = new Properties();
prop.setProperty("my.name", "John");
prop.load(input);
String output=  prop.getProperty(his.name);
System.out.println(output);

Expected Results:

hisNameIsJohn
2 Answers

The Apache Commons Configuration Project has an implementation capable of doing variable interpolation.

Read the section named Variable Interpolation

application.name = Killer App
application.version = 1.6.2
application.title = ${application.name} ${application.version}

You would need this third-party library in your class path, but on the other hand you will not have to worry about writing yet another implementation for this :)

You might like to read the Properties How To as well.

Posting the solution using org.apache.commons.configuration.PropertiesConfiguration

PropertiesConfiguration prop = new PropertiesConfiguration(new File("path/settings.properties"));
    prop.addProperty("name", "John");
    prop.getProperty(his.name);

In, "settings.properties" file.

his.name=hisNameIs${name}
Related