有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java是否用实际值替换环境变量占位符?

在我的申请中。属性文件我使用的是这样的键和值

report.custom.templates.path=${CATALINA_HOME}\\\\Medic\\\\src\\\\main\\\\reports\\\\AllReports\\\\

我需要用实际路径替换${CATALINA_HOME}

{CATALINA_HOME} = C:\Users\s57893\softwares\apache-tomcat-7.0.27

这是我的代码:

public class ReadEnvironmentVar {  

 public static void main(String args[]) {

    String path = getConfigBundle().getString("report.custom.templates.path");
    System.out.println("Application Resources : " + path);
    String actualPath = resolveEnvVars(path);
    System.out.println("Actual Path : " + actualPath);

   }

private static ResourceBundle getConfigBundle() {
    return ResourceBundle.getBundle("medicweb");
 }

private static String resolveEnvVars(String input) {
    if (null == input) {
        return null;
     }

    Pattern p = Pattern.compile("\\$\\{(\\w+)\\}|\\$(\\w+)");
    Matcher m = p.matcher(input);
    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 ? "" : envVarValue);
     }
    m.appendTail(sb);
    return sb.toString();
  }
}

从我的代码中,我得到的结果是-

实际路径:

 C:Userss57893softwaresapache-tomcat-7.0.27\Medic\src\main\reports\AllReports\

但我需要结果-

实际路径:

C:\Users\s57893\softwares\apache-tomcat-7.0.27\Medic\src\main\reports\AllReports\

请给我举个例子


共 (1) 个答案

  1. # 1 楼答案

    由于appendReplacement()的工作方式,您需要避开环境变量中的反斜杠。从the Javadocs

    Note that backslashes (\) and dollar signs ($) in the replacement string may cause the results to be different than if it were being treated as a literal replacement string. Dollar signs may be treated as references to captured subsequences as described above, and backslashes are used to escape literal characters in the replacement string.

    我会使用:

    m.appendReplacement(sb, 
        null == envVarValue ? "" : Matcher.quoteReplacement(envVarValue));