java – inheriting the user.home property within my custom .properties file – Education Career Blog

Can I do something like working-dir="file:${user.home}/some-directory" within my .properties file? I am using ResourceBundle to load configuration from a .properties file and I would to inherit a system property key such as user.home for my working-dir property. It would be nice to be able to do this since I can have different versions of the .properties in resource directory of the source package and test package respectively. I want to define different values for working-dir for my production and testing environment.

,

You cannot do that directly, however you can parse your properties in your code and programatically expand the variables, e.g.

  • Search for the pattern ${varname} in your property
  • Get the value of varname from the system properties
  • Replace ${varname} with the value of system property varname

Here is a simple implementation of the above:

String property = "file:${user.home}/some-directory";

StringBuffer sb = new StringBuffer();
Pattern pattern = Pattern.compile("\\$\\{(.+)\\}");
Matcher matcher = pattern.matcher(property);
while (matcher.find())
{
    String key = matcher.group(1);
    String val = System.getProperty(key);
    if (val != null)
    {
        matcher.appendReplacement(sb, Matcher.quoteReplacement(val));
    }
}
matcher.appendTail(sb);
System.out.println(sb.toString());

,

Just tried Apache commons configuration‘s variable interpolation and it works perfect.

Leave a Comment