如何在java MessageFormat.format方法中使用FieldPosition参数?

时间:2012-01-19 00:22:10

标签: java

如何在java中的MessageFormat.format方法中使用FieldPosition参数?在我在网上看到的所有例子中,都没有使用FieldPosition参数。这个论点用于什么吗?我在这里查看规范:http://docs.oracle.com/javase/1.5.0/docs/api/java/text/MessageFormat.html。方法签名复制如下。

public final StringBuffer format(Object[] arguments,
                                 StringBuffer result,
                                 FieldPosition pos)

1 个答案:

答案 0 :(得分:2)

FieldPosition 使用两个索引跟踪格式化输出中字段的位置:字段的第一个字符的索引和字段的最后一个字符的索引。

您可以使用

  NumberFormat numForm = NumberFormat.getInstance();
    StringBuffer dest1 = new StringBuffer();
    FieldPosition pos = new FieldPosition(NumberFormat.INTEGER_FIELD);
    BigDecimal bd1 = new BigDecimal(22.3423D);
    dest1 = numForm.format(bd1, dest1, pos);
    System.out.println("dest1 = " + dest1);
    System.out.println("INTEGER portion is at: " + pos.getBeginIndex() +
        ", " + pos.getEndIndex());
    pos = new FieldPosition(NumberFormat.FRACTION_FIELD);
    dest1 = numForm.format(bd1, dest1, pos);
    System.out.println("FRACTION portion is at: " + pos.getBeginIndex() +
            ", " + pos.getEndIndex());

输出

 dest1 = 22.342
 INTEGER portion is at: 0, 2
 FRACTION portion is at: 9, 12

对于DateFormat

 FieldPosition pos = new FieldPosition(DateFormat.YEAR_FIELD);
 FieldPosition pos2 = new FieldPosition(DateFormat.MONTH_FIELD);

关于MessageFormat.format中使用的FieldPosition参数

// Create a pattern for our MessageFormat object to use.
    String pattern = "he bought {0,number,#} "
            + "apples for {1,number,currency} " + "on    {2,date,MM/dd/yyyy}.";
    String pattern2 = "I bought {0} " + "apples for {1} " + "on {2}.";
    // Create values to populate the position in the pattern.
    Object[] values = { 5, 7.53, new Date() };
    // Create a MessageFormat object and apply the pattern
    // to it.
    MessageFormat mFmt = new MessageFormat(pattern);
    StringBuffer buf = new StringBuffer("Wow,");
    System.out.println(mFmt.format(values, buf, null));