MessageFormat.format用法实例

来自 Java中的MessageFormat.format用法实例


这篇文章主要介绍了Java中的MessageFormat.format用法实例,本文先是讲解了MessageFormat的语法,然后给出了多个操作实例,需要的朋友可以参考下
MessageFormat本身与语言环境无关,而与用户提供给MessageFormat的模式和用于已插入参数的子格式模式有关,以生成适用于不同语言环境的消息。
MessageFormat模式(主要部分): 
FormatElement:
         { ArgumentIndex }:是从0开始的入参位置索引。
         { ArgumentIndex , FormatType }
         { ArgumentIndex , FormatType , FormatStyle }
 
 FormatType: :指定使用不同的Format子类对入参进行格式化处理。值范围如下:
         number:调用NumberFormat进行格式化
         date:调用DateFormat进行格式化
         time:调用DateFormat进行格式化
         choice:调用ChoiceFormat进行格式化
 
 FormatStyle::设置FormatType中使用的格式化样式。值范围如下:
         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是为了生成日期格式的值、不同精度的数字、百分比类型等等。
 
实例:
1、ArgumentIndex必须是非负整数,它的个数不只限于0到9这10个,它可以用0到9的数字组成,因此可以有好多个,如:
String msg = "{0}{1}{2}{3}{4}{5}{6}{7}{8}";  
Object [] array = new Object[]{"A","B","C","D","E","F","G","H","I",};         
String value = MessageFormat.format(msg, array);  
  
System.out.println(value);  // 输出:ABCDEFGHI  


2、格式化字符串时,两个单引号才表示一个单引号,单个单引号会被省略,除非中文单引号不会被省略,如:

String value = MessageFormat.format("oh, {0} is 'a' pig", "ZhangSan");  
  
System.out.println(value);  // 输出:oh, ZhangSan is a pig  
给字母a加上单引号,如:

String value = MessageFormat.format("oh, {0} is ''a'' pig", "ZhangSan");
System.out.println(value);  // 输出:oh, ZhangSan is 'a' pig
如果需要显示双引号要进行转移,比如:String msg = "oh, {0} is "a" pig";
3、单引号会使其后面的占位符均失效,导致直接输出占位符。

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

使用双引号和两个单引号没有关系,比如

String value = MessageFormat.format("oh, ''{0}'' is a pig", "ZhangSan");
System.out.println(value);  // 输出:oh, 'ZhangSan' is a pig
又比如,使用子格式模式,多了一个单引号:

String value = MessageFormat.format("oh, {0,number,#.#} is good num", Double.valueOf("3.1415"));
System.out.println(value);  // 输出:oh, 3.1 is good num
3、无论是有引号字符串还是无引号字符串,左花括号都是不支持的,如:
String value = MessageFormat.format("oh, } is good num", Double.valueOf("3.1415"));
System.out.println(value);  // 输出:oh, } is good num
如果使用左花括号会出现异常

String value = MessageFormat.format("oh, { is good num", Double.valueOf("3.1415"));
System.out.println(value);  // java.lang.IllegalArgumentException: Unmatched braces in the pattern.
因此要使用到左花括号需要使用单引号配合使用
MessageFormat.format("'{'{0}}", "X-rapido"); // {X-rapido}
还有一个有趣的现象,如果出现两个或2个以上左花括号,就会出现分割字符串,但是右花括号就没问题,虽然没有任何意义,实际应用我们也用不到

String value = MessageFormat.format("oh, {{ is good num", "d");
System.out.println(value);  // oh, 

String value = MessageFormat.format("oh, }} is good num", "d");
System.out.println(value);  // oh, }} is good num 

每调用一次MessageFormat.format方法,都会新创建MessageFormat的一个实例,相当于MessageFormat只使用了一次。MessageFormat类的format方法如下:
public static String format(String pattern, Object ... arguments)   
{  
    MessageFormat temp = new MessageFormat(pattern);  
    return temp.format(arguments);  
}  
  因此若要多次格式同一个模式的字符串,那么创建一个MessageFormat实例在执行格式化操作比较好些
 
String message = "oh, {0} is a pig";  
MessageFormat messageFormat = new MessageFormat(message);  
Object[] array = new Object[]{"ZhangSan"};  
String value = messageFormat.format(array);  
  
System.out.println(value); 


ChoiceFormat 允许将格式应用到某个范围的数。它通常用于在 MessageFormat 中处理复数。使用按升序排列的 double 列表指定 choice,列表中每一项都指定一个到下一项的半开区间: 
    当且仅当 limit[j] <= X < limit[j+1] 时,X 匹配 j
    
  
private static void choiceFormat() {
        MessageFormat form = new MessageFormat("{0} say: The disk "{1}" contains {2}.");
        double[] filelimits = {0,1,2};  //区间 [0,1) [1,2) [2,+)
        String[] filepart = {"no files","one file","{2,number} files"};//使用
        ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
        form.setFormatByArgumentIndex(2, fileform);//参数设置在模板form的{2}

        int fileCount = 1273;
        String diskName = "MyDisk";
        Object[] testArgs = {"I", diskName,new Long(fileCount)};


        System.out.println(form.format(testArgs));//I say: The disk "MyDisk" contains 1,273 files.
    }
来自:MessageFormat和ChoiceFormat的使用方法
package java_test.text;


import java.text.ChoiceFormat;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.Format;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MessageFormatT {
    public static void main(String[] args) {


        String value = MessageFormat.format("oh, ''{0}'' is a pig", "ZhangSan");
        System.out.println(value);  // 输出:oh, 'ZhangSan' is a pig //单引号起转义作用
        int planet = 7;
        String event = "a disturbance in the Force";
        String result = MessageFormat.format(
                "At {1,time} on {1,date}, there was {2} on planet {0,number,integer}.",
                planet, new Date(), event);
        System.out.println(result);


        formatText();
        formatNumber();
        formatDate();
        subFormat();
        choiceFormat();
    }


    private static void choiceFormat() {
        MessageFormat form = new MessageFormat("{0} say: The disk "{1}" contains {2}.");
        double[] filelimits = {0,1,2};
        String[] filepart = {"no files","one file","{2,number} files"};//使用
        ChoiceFormat fileform = new ChoiceFormat(filelimits, filepart);
        form.setFormatByArgumentIndex(2, fileform);//模板设置在上面的{2}


        int fileCount = 1273;
        String diskName = "MyDisk";
        Object[] testArgs = {"I", diskName,new Long(fileCount)};


        System.out.println(form.format(testArgs));//I say: The disk "MyDisk" contains 1,273 files.
    }




    /***
     * 对应的{0},{1},{2},{3},{4},{5},{6}
     * 为{"一","二","三","四","五","六","日"}
     */
    public static void formatText(){
        String message = "今天是星期{6}";
        String [] day={"一","二","三","四","五","六","日"};
        //输出结果为“今天是星期日”
        System.out.println(MessageFormat.format(message,day));
    }


    public static void formatNumber(){
        String message = "圆周率是{0,number,#.#}";
        Double yl[] = {new Double(3.1415)};
        //输出3.1415
        System.out.println(MessageFormat.format(message,yl));
    }


    /***
     * number:调用NumberFormat进行格式化
     * date:调用DateFormat进行格式化
     * time:调用DateFormat进行格式化
     * choice:调用ChoiceFormat进行格式化
     */
    public static void formatDate(){
        String message = "今天是:{0,date,yyyy/MM/dd HH:mm:ss}";
        Date date = new Date();
        System.out.println(MessageFormat.format(message,date));
        System.out.println(MessageFormat.format("今天是:{0,time}",date));
        System.out.println(MessageFormat.format("今天是:{0,date}",date));
    }


    public static void subFormat(){
        DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
        String message = "今天是:{0}==={1}";
        DecimalFormat numFormat = new DecimalFormat("###,###,###");
        MessageFormat mf = new MessageFormat(message);
        Date date = new Date();
        Double d1 = new Double(12345666);
        //设置{0}使用的格式化方式和{1}使用的格式化方式
        mf.setFormatsByArgumentIndex(new Format[]{format,numFormat});
        //输出"今天是:2015/04/01 22:24:24===12,345,666"
        System.out.println(mf.format(new Object[]{date,d1}));
    }
}




原文地址:https://www.cnblogs.com/thewindkee/p/12873193.html