2016-02-11 33 views
2

我使用Apache配置以下配置设置:是否有阿帕奇PropertiesConfiguration使用占位的方式

import org.apache.commons.configuration.Configuration; 
import org.apache.commons.configuration.PropertiesConfiguration; 

Configuration config = new PropertiesConfiguration("config.properties"); 

我想知道是否有某种方式使用占位符的属性文件?例如,我想有这样的:

some.message = You got a message: {0} 

并能够在为{0}占位符的值传递。通常情况下,您通常可以执行类似config.getString("some.message", String[] of values)的操作,但不会看到类似的内容。

回答

1

据我所知,Configuration类不提供任何格式化程序。因此,为了您的任务

  1. 您可以使用MessageFormat,因为它是由Bilguun建议的。请注意,该格式的方法是static。可以使用String.format函数。

实例是波纹管:

config.properties

enter some.message.printf=%1$s\, you've got a message from %2$s \n 
some.message.point.numbers =Hey {0}\, you got message: {1}! 

实施例类

import org.apache.commons.configuration.Configuration; 
import org.apache.commons.configuration.ConfigurationException; 
import org.apache.commons.configuration.PropertiesConfiguration; 

import java.text.MessageFormat; 

public class ConfigurationTest { 


    public static void main(String[] args) throws ConfigurationException { 
     Configuration config = new PropertiesConfiguration("config.properties"); 

     String stringFormat = String.format(config.getString("some.message.printf"), "Thomas", "Andrew"); 
     // 1 String format 
     System.out.println(stringFormat); 
     // 2 Message Format 
     System.out.println(MessageFormat.format(config.getString("some.message.point.numbers"), "Thomas", "Hello")); 
    } 
} 
1

我相信你可以用属性文件的占位符来获取属性值,然后使用MessageFormat来将消息格式化为你所期望的。比方说,你有你的属性文件以下属性:

some.message = "Hey {0}, you got message: {1}!" 

使您得到和格式化此属性,如:

message will be "Hey {0}, you got message: {1}!"  
String message = config.getString("some.message"); 

MessageFormat mf = new MessageFormat(""); 

//it will print: "Hey Thomas, you got message: 1" 
System.out.println(mf.format(message, "Thomas", 1)); 

另外,如果你可以使用系统变量或环境变量,如果它是不动态更改