在我的属性文件中,我使用的系统变量如下:
log4j.appender.RollingFile.File=${workspace.logs}/my.log
我正在读这样的财产:
Properties p = new Properties();
p.load(new FileInputStream("logger.properties"));
String label = (String) p.get("log4j.appender.RollingFile.File");
System.out.println(label);
结果是:
${workspace.logs}/my.log
如何使用评估变量打印结果? e.g。
C:/logs/my.log
?
EDITED
我相信我可以在正则表达式中执行 - 正如一些人所建议的那样 - 所以完美的解决方案将是如何用System.property替换$ {..}内容
答案 0 :(得分:1)
首先我们必须找到$ {}内的内容。提取后,将整个事物替换为环境属性中的值(希望 workspace.logs 是一个Env变量
)... 为了得到我们可以使用
System.getenv()
然后我们可以使用replace方法替换相同的方法。如果存在多个env_variable Occurrences
,这应该在循环中完成Properties p = new Properties();
p.load(new FileInputStream("c:\\log4j.properties"));
String label = (String) p.get("log4j.appender.RollingFile.File");
int firstIndex=label.indexOf("${");
int lastIndex=label.indexOf("}");
String tempKey =label.substring(firstIndex+2,lastIndex);
String tempValue =System.getenv(tempKey);
label=label.replaceFirst("\\$\\{((?s).*)\\}",tempValue);
System.out.println(label);
将输出为
c:/log/my.log
答案 1 :(得分:0)
Java不会自动替换它们,它们只被视为字符串。您必须通过System.getenv()
进行变量替换。
在此之前,您必须使用正则表达式或其他一些机制识别并使用变量。
Pattern p = Pattern.compile("\\$\\{([0-9a-zA-Z.@]+)}");
Matcher m = p.matcher(label);
if(m.find())
{
String var = m.group();
String envVar = var.replace("${","").replace("}","");
label = label.replace(var,System.getenv(envVar));
}
请注意,上面的代码假设您只有一行中的一个变量,您必须使用while循环而不是if。另请注意,上面的代码可能在语法上不正确,因为我没有任何Java IDE。
答案 2 :(得分:0)
对于一个非常快速和肮脏的解决方案,您甚至可以使用替换循环,但这不会考虑转义占位符分隔符(如果您有一天会在您的值中提出文字${foo}
,那该怎么办?)。我手工编写了一个简单的Lexer / Parser夫妇来解决类似的问题,这不是一个非常复杂的任务。
但是我建议你将第一个阶段封装在模板引擎中,以便使用不同的实现。必须使用模板引擎创建一个中间文本,然后使用如下:
// Load the bindings from your configuration
Map<String, Object> bindings = loadBindings();
Template tpl = new Template("log4j.properties");
tpl.bind(bindings);
tpl.compile();
Properties resolvedConfiguration = new Properties();
Reader in = new StringReader(tpl.getText());
resolvedConfiguration.load(in);
不幸的是我无法找到一个模板引擎,可以配置足以满足我对占位符分隔符和变量解析的需求,并且必须编写我自己的,但这是一个简单的任务(几个小时的工作),因为语言并不复杂。
答案 3 :(得分:0)
如果您已正确设置系统变量,那么您将只能使用
${sys:workspace.logs}
获得预期的输出。
在http://logging.apache.org/log4j/2.x/manual/lookups.html
中提及所以实际上你需要编写log4j.appender.RollingFile.File = $ {sys:workspace.logs} /my.log
问题解决了。