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

xiaoxiao2021-02-27  427

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

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

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

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

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

1、配置文件如下:

2、代码如下:

@Test public void queryDictionary() throws Exception { Properties prop = new Properties(); InputStream in = Test.class.getClassLoader().getResourceAsStream( "errorMessage.properties"); prop.load(in); String no="20"; String Name="11"; String newName="24"; //参数 String params[]={no,Name,newName}; //从配置文件中读取模板字符串替换 String msg= MessageFormat.format(prop.getProperty("0010010005"),params); System.out.println("模板字符串:"+prop); System.out.println("替换后的字符串:"+msg); }

执行结果是:

模板字符串:该供应商分类编码已经存在 : 编码{0}已经被{1}占用,导入类别名称为{2} 替换后的字符串:该供应商分类编码已经存在 : 编码20已经被11占用,导入类别名称为24

 

注意:配置文件中的占位符{}从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,#.#}里面的#.#就属于子格式模式。

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

只要前进的方向正确,就算走得再慢,那也是在进步。
转载请注明原文地址: https://www.6miu.com/read-1945.html

最新回复(0)