Java关于Properties用法(二)——替换配置文件中的参数

来源:互联网 发布:python subprocess cwd 编辑:程序博客网 时间:2024/06/02 02:33

Java关于Properties用法(二)——替换配置文件中的参数

上一章讲了配置文件的基本用法,虽然上一章已经可以解决一些需求,但还不些不足之处。假如,配置文件里面的字符串有一部分需要经常变动,另外一些不需要,上一章的方法就不方便了,所以这章主要讲如何在配置文件中使用参数,然后替换字符串里面的参数值。


一、使用类MessageFormat替换配置文件中的参数

MessageFormat 提供了以与语言无关方式生成连接消息的方式。使用此方法构造向终端用户显示的消息。

MessageFormat 获取一组对象,格式化这些对象,然后将格式化后的字符串插入到模式中的适当位置。

注:MessageFormat 不同于其他 Format 类,因为 MessageFormat 对象是用其构造方法之一创建的(而不是使用 getInstance 样式的工厂方法创建的)。工厂方法不是必需的,因为MessageFormat 本身不实现特定于语言环境的行为。特定于语言环境的行为是由所提供的模式和用于已插入参数的子格式来定义的。

简单来说MessageFormat是一个字符串格式化类,主要使用它的format()方法来替换一个字符串的参数。

1、配置文件如下:

image

2、代码如下:

复制代码
package test.email;import java.io.IOException;import java.io.InputStream;import java.text.MessageFormat;import java.util.Properties;public class Test {    public static void main(String[] args) throws IOException {        Properties prop = new Properties();        InputStream in = Test.class.getClassLoader().getResourceAsStream(                "emailContent.properties");                prop.load(in);        //参数        String params[]={"‘张三’ ","13488888888","70.8"};        //从配置文件中读取模板字符串替换        String msg=MessageFormat.format(prop.getProperty("text"),params);        System.out.println("模板字符串:"+prop);        System.out.println("替换后的字符串:"+msg);            }}
复制代码

执行结果是:

模板字符串:{text=尊敬的{0}用户你好,您的手机号码{1}已经欠费{2},请尽快充值}
替换后的字符串:尊敬的‘张三’ 用户你好,您的手机号码13488888888已经欠费70.8,请尽快充值

 

注意:配置文件中的占位符{}从0开始,与参数数组下标一一对应!!!

二、MessageFormt的模式

MessageFormat用来格式化一个消息,通常是一个字符串,比如:

String str = "I'm not a {0}, age is {1,number,short}", height is {2,number,#.#};

而MessageFormat可以格式化这样的消息,然后将格式化后的字符串插入到模式中的适当位置,比如:

将str中的{0}用"pig"替换,{1,number,short}用数字8替换,{2,number,#.#}用数字1.2替换。

那么最终用户得到的是一个格式化好的字符串"I'm not a pig, age is 8, height is 1.2"。

MessageFormat本身与语言环境无关,而与用户提供给MessageFormat的模式和用于已插入参数的子格式模式有关,以生成适用于不同语言环境的消息。

MessageFormat模式(主要部分):

FormatElement:
         { ArgumentIndex }
         { ArgumentIndex , FormatType }
         { ArgumentIndex , FormatType , FormatStyle }

FormatType:
         number

         date

         time

         choice(需要使用ChoiceFormat)

FormatStyle:
         short
         medium
         long
         full
         integer
         currency
         percent
SubformatPattern(子模式)

还以str为例,在这个字符串中:

1、{0}和{1,number,short}和{2,number,#.#};都属于FormatElement,0,1,2是ArgumentIndex。

2、{1,number,short}里面的number属于FormatType,short则属于FormatStyle

3、{1,number,#.#}里面的#.#就属于子格式模式。

指定FormatTypeFormatStyle是为了生成日期格式的值、不同精度的数字、百分比类型等等

只要前进的方向正确,就算走得再慢,那也是在进步。
原创粉丝点击