2016-02-11 32 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)); 

另外,如果你可以使用系統變量或環境變量,如果它是不動態更改