Resolve environment variable in a property value Tag(s): Language


A common way to use environment variables in a Properties file is to refer to them with the following syntax :
value=The value is ${variableName}
The regular Properties class can't resolve the real value form the environment variable named variableName.

One way is to use this small utility

import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class PropertiesUtils {

  private PropertiesUtils() {}

  private static String resolveValueWithEnvVars(String value) {
    if (null == value) {
        return null;
     }

    Pattern p = Pattern.compile("\\$\\{(\\w+)\\}|\\$(\\w+)");
    Matcher m = p.matcher(value);
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        String envVarName = null == m.group(1) ? m.group(2) : m.group(1);
        String envVarValue = System.getenv(envVarName);
        m.appendReplacement(sb,
            null == envVarValue ? "" : Matcher.quoteReplacement(envVarValue));
     }
    m.appendTail(sb);
    return sb.toString();
  }
}
to use it :
  public static void main(String[] args) {
    // For the demo, create a Properties, normally you will read Properties from file
    Properties p = new Properties();
    p.put("path", "${TEMP}\\${USERDOMAIN}");

    System.out.println("path value : "
       + PropertiesUtils.resolveValueWithEnvVars(p.getProperty("path")));
    /*
     * output on my machine :
     *   path value :C:\Users\REAL_U~1\AppData\Local\Temp\RealNet001
     *               ------------------------------------ ----------
     *                            TEMP                    USERDOMAIN
     */
  }
NOTE: Apache Commons Lang StrSubstitutor class can be used to do something similar but with Java System Properties (not OS environment variable) or user-supplied map of values.
blog comments powered by Disqus