使用Properties动态读取/添加conf文件参数的值

我的conf文件中有如下消息。

text.message = Richard必须在01/06/2012 / 1days

所有突出显示的字段都是可变的

我想阅读这个text.me字符串并使用Properties插入我的java中的值。

我知道如何使用Prop读取整个字符串,但不知道如何读取如上所述的字符串。

text.message = #name#必须在text.message = #name# #/#days#中转到#place#。

  1. 如何使用Properties从conf中读取上述字符串并动态插入数据?

  2. 它可以是字符串中的日期或天数。 我如何在这些参数之间打开和关闭?

谢谢你。

您可以使用MessageFormat API。

开球示例:

 text.message = {0} has to go to {1} in {2,date,dd/MM/yyyy} / {3} 

 String message = properties.getProperty("text.message"); String formattedMessage = MessageFormat.format(message, "Richard", "School", new Date(), "1days"); System.out.println(formattedMessage); // Richard has to go to School in 31/05/2012 / 1days 

您可以使用MessageFormat类,它将字符串中的动态占位符替换为所需的值。

例如,以下代码……

 String pattern = "{0} has to go to {1} in {2,date} / {3,number,integer} days."; String result = MessageFormat.format(pattern, "Richard", "school", new Date(), 5); System.out.println(result); 

…将产生以下输出:

 Richard has to go to school in 31-May-2012 / 5 days. 

您可以从Properties对象中获取模式,然后应用MessageFormat转换。

您可以尝试使用此代码来获取有关属性文件的帮助。

App.java

 import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; import java.util.Properties; public class App { public static void main(String[] args) { Properties prop = new Properties(); OutputStream output = null; try { output = new FileOutputStream("config.properties"); // set the properties value prop.setProperty("database", "localhost"); prop.setProperty("dbuser", "ayushman"); prop.setProperty("dbpassword", "password"); // save properties to project root folder prop.store(output, null); } catch (IOException io) { io.printStackTrace(); } finally { if (output != null) { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } } } } 

产量

config.properties

 #Fri Jan 17 22:37:45 MYT 2014 dbpassword=password database=localhost dbuser=ayushman