• Java魔法堂:初探MessageFormat.format和ChoiceFormat


    一、前言                              

      刚开始从.net的转向java的时候总觉得 String.format 用得不习惯,希望格式模版会这样 {0}, this is {1}'s cat.{1},this is {0}'s dog. 而不是 %1$s,this is %2$s's cat.%2$s,this is %1$s's dog. 。后来发现 java.text.MessageFormat.format 可以满足我这个小小的愿望。

    二、静态方法 java.text.MessageFormat.format                 

      方法定义:

    String MessageFormat.format(String fmt, Object...args)

      入参fmt为MessageFormat模式参数。

    三、MessageFormat模式                      

      格式:  ArgumentIndex[,FormatType[,FormatStyle]] 

      ArgumentIndex ,是从0开始的入参位置索引。

      FormatType ,指定使用不同的Format子类对入参进行格式化处理。值范围如下:

         number:调用NumberFormat进行格式化

         date:调用DateFormat进行格式化

         time:调用DateFormat进行格式化

         choice:调用ChoiceFormat进行格式化

      FormatType ,设置FormatType中使用的格式化样式。值范围如下:

        short,medium,long,full,integer,currency,percent,SubformPattern(子格式模式,形如#.##)

      注意: FormatType 和 FormatStyle 主要用于对日期时间、数字、百分比等进行格式化。

      示例——将数字1.23格式为1.2:

    double num = 1.23;
    String str = MessageFormat.format("{0,number,#.#}", num);

    四、MessageFormat注意点                    

      1. 两个单引号才表示一个单引号,仅写一个单引号将被忽略。

      2. 单引号会使其后面的占位符均失效,导致直接输出占位符。

    MessageFormat.format("{0}{1}", 1, 2); // 结果12
    MessageFormat.format("'{0}{1}", 1, 2); // 结果{0}{1}
    MessageFormat.format("'{0}'{1}", 1, 2); // 结果{0}

    因此可以用于输出左花括号(单写左花括号会报错,而单写右花括号将正常输出)

    MessageFormat.format("'{'{0}}", 2); // 结果{2

    因此前言中的示例应该写为

    {0}, this is {1}''s cat.{1},this is {0}''s dog.

    五、类层级关系                                

                                             |-- java.text.MessageFormat

    顶层抽象类java.text.Format—|                                         |--java.text.ChoiceFormat

                                             |--java.text.NumberFormat—|

                   |               |--java.text.DecimalFormat

                   |

                                             |--java.text.DateFormat—java.text.SimpleDateFormat

       1. DecimalFormat

           用于格式化十进制实数。通过格式字符串来自定义格式化类型,舍入方式为half-even(四舍五入)。

           格式化模式: 正数子模式;负数子模式 ,如 0.00;-0.00 ,简写为 0.00 。

           模式中的占位符:

         0 ,代表该为位为数字,若不存在则用0填充

             # ,代表该为位为数字

         , ,代表分隔符, 如模式为 #,# ,那么格式化10时会返回1,0

       2. ChoiceFormat

        相当于以数字为键,字符串为值的键值对。分别使用一组double类型的数组作为键,一组String类型的数组作为值,两数组相同索引值的元素作为一对。

        示例——基本用法

    double[] limit = {0,1,3};
    String[] format = {"hello0", "hello1", "hello3"};
    ChoiceFormat cf = new ChoiceFormat(limit, format);
    for(int i = 0; i < 4; ++i){
      System.out.println(cf.format(i));
    }
    /* 输出
     * hello0
     * hello1
     * hello0
     * hello3
     */

       注意:当找不到对应的键值对时,则使用第一或最后一对键值对。

       示例——结合MessageFormat使用

    double[] limit = {0, 1};
    String[] format = {"Hello0", "Hello1{1}"};
    ChoiceFormat cf = new ChoiceFormat(limit, format);
    MessageFormat mf = new MessageFormat("{0}");
    mf.setFormatByArgumentIndex(0, cf);
    for (int i = 0; i < 2; ++i){
        System.out.println(mf.format(new Object[]{new Integer(i), new Integer(i+1)}));
    }
    /* 输出
     * Hello0
     * Hello12
     */

    六、性能问题                                  

      由于静态方法 MessageFormat.format 内部是

    public static String format(String pattern, Object ... arguments)   
    {  
        MessageFormat temp = new MessageFormat(pattern);  
        return temp.format(arguments);  
    }  

      因此若要多次格式同一个模式的字符串,那么创建一个MessageFormat实例在执行格式化操作比较好些。

    七、总结                                  

      对于简单的格式化或字符串组装, MessageFormat.format方法 使用更方便些,但要格式化处理更丰富的话要是用 String.format方法 吧!  

      尊重原创,转载请注明来自:http://www.cnblogs.com/fsjohnhuang/p/4095059.html  ^_^肥仔John  

    八、参考                                  

      http://zqc-0101.iteye.com/blog/114014

  • 相关阅读:
    使用kindeditor获取不到富文本框中的值
    ASP.NET中的文件操作(文件信息,新建,移动,复制,重命名,上传,遍历)
    2018 遇到selenium.common.exceptions.WebDriverException问题
    DataTable与实体类互相转换
    反射load,loadfile,LoadFrom区别
    DbSet.Attach(实体)与DbContext.Entry(实体).State = EntityState.Modified 区别
    .net 面试总结
    C# Linq 常用查询操作符
    windows下nginx的安装及使用
    熊猫热土-环汶川50公里越野赛赛记
  • 原文地址:https://www.cnblogs.com/fsjohnhuang/p/4095059.html
Copyright © 2020-2023  润新知