MessageFormat和String类中的format使用

MessageFormat(常用)

MessageFormat提供了以语言环境无关的生成连接消息的方式。 常用MessageFormat的静态方法format,该方法接收一个字符串的模式和一组对象(对象数组),按照模式形式将格式化的对象插入到模式中,然后返回字符串结果。

MessageFormat占位符由三种书写格式:

  1. {index}:
  2. {index,formatType}:
  3. {index,formatType,formatStyle}

index表示数字角标。FormatType包括number、date、 time、choice等。FormatStyle包括short、medium、long、full、integer、currency、percent等

number对应了NumberFormat,其子格式对应了DecimalFormat date和time对应了DateFormat,其子格式对应了SimpleDateFormat choice对应了ChoiceFormat

Demo:

    public static void main(String[] args) {
        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); //At 15:38:07 on 2019-6-4, there was a disturbance in the Force on planet 7.
    }

备注:若你的模版被多次使用到,也可以使用MessageFormat的构造方法传入pattern string(模式字符串),然后调用普通的format方法。若只执行一次,可以用静态方法~

注意指定了formatType后,第三个参数formatStyle并不能随意写的。至于formatType和formatStyle的对应关系,此处不解释了

最后,我们用java处理国际化的时候,我们的properties配置文件里经常可议看到{0} {1}这样的占位符,其实最终都是交给MessageFormat去处理了的~~

注意,注意,注意:Format中的子类都是不同步,所以需要注意线程安全问题

String类中的format方法

String因为过于常用,所以在JDK5的时候它提供了静态方法format方法来方便我们对字符串进行格式化。 直接看例子吧~~

    public static void main(String[] args) {
        String result1 = String.format("小明今年%d岁,他住在%s,他的月工资有%.2f", 25, "北京市", 6633.435);
        System.out.println(result1);//输出:小明今年25岁,他住在北京市,他的月工资有6633.44

        /****************************************************/

        double num = 123.4567899;
        String result2 = String.format("%e", num);
        System.out.println(result2);//输出:1.234568e+02
    }

猜你喜欢

转载自blog.csdn.net/yunxing323/article/details/111825259