Share this page 

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
     */
  }

Apache Commons Text StringSubstitutor can be used to do something similar.

import java.util.Properties;
import org.apache.commons.text.StringSubstitutor;

public class EnvSubst {
   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("tempfolder", "${TEMP}");

      System.out.println("path value : " +
          new StringSubstitutor(System.getenv()).replace(p.get("tempfolder")));
   }
}
pom.xml
   <dependency>
       <groupId>org.apache.commons</groupId>
       <artifactId>commons-text</artifactId>
       <version>1.3</version>
   </dependency>