Java 字符串格式化 —— java.util.Formatter

java.util.Formatter是JDK1.5新增的类,支持相似C中的printf风格的字符串格式化工做html


Formatter有4个构造方法,以下:java

public Formatter()api

public Formatter(Appendable a)oracle

public Formatter(Locale l)ui

public Formatter(Appendable a, Locale l)spa

构造方法主要用于设置Formatter的缓冲器和Locale,默认的状况下,Formatter使用StringBuilder做为缓冲器,使用Locale.getDefault()做为locale。code


Formatter的使用方法以下(摘自JDK DOC):orm

 StringBuilder sb = new StringBuilder();
 // Send all output to the Appendable object sb
 Formatter formatter = new Formatter(sb, Locale.US);

 // Explicit argument indices may be used to re-order output.
 formatter.format("%4$2s %3$2s %2$2s %1$2s", "a", "b", "c", "d")
 // -> " d  c  b  a"

 // Optional locale as the first argument can be used to get
 // locale-specific formatting of numbers.  The precision and width can be
 // given to round and align the value.
 formatter.format(Locale.FRANCE, "e = %+10.4f", Math.E);
 // -> "e =    +2,7183"

 // The '(' numeric flag may be used to format negative numbers with
 // parentheses rather than a minus sign.  Group separators are
 // automatically inserted.
 formatter.format("Amount gained or lost since last statement: $ %(,.2f", balanceDelta);
 // -> "Amount gained or lost since last statement: $ (6,217.58)"

例子中,先new一个Formatter对象,而后调用Formatter的format方法,这时Formatter内部的缓冲器就储存了格式化后的字符串,而后能够用toString方法取出。htm


更为通常的用法是使用String.format,String.format经过Formatter实现字条串格式对象

public static String format(String format, Object ... args) {
    return new Formatter().format(format, args).toString();
}


或者在输出流中使用

System.out.format("Local time: %tT", Calendar.getInstance());


format方法的主要参数分两部分,格式字符串和可变的格式化参数


格式字符串有一套本身的语法,它由固定文本或者格式描述符组成。描述符的格式以下:

 %[argument_index$][flags][width][.precision]conversion

argument_index 是一个整数,代表使用的参数的位置,例如

System.out.format("%d %d", 1, 2);        // 输出 1 2
System.out.format("%1$d %d", 1, 2);      // 输出 1 1

flags 是一组用于修饰输出的字条

width 是一个非负的整数,用于指定写到绥中的最小长度

precision 是一个非负整数,通常用于指定数字的精度,依赖conversion 

conversion 必须有值,用于指定参数如何转换


conversion  主要有如下几组字符(便可以转换的类型)

's''S'             要求参数实现了Formattable,而后调用它的formatTo方法获得结果

'c''C'        字符

'd'             十进制整数

'o'             八进制整数

'x''X'        十六进制整数

'e''E'        科学计数法浮点数

'f'             浮点数

't''T'        时间日期


flags 主要有如下几种用法

'-'                            左对齐

'#'                            依赖于conversion,不一样的conversion,该flag的含义不同

'+'                            结果带正负号

' '                             结果带前置空格

'0'                            若是结果不知足宽度(width 参数)的要求,用0字符填充

','                            数字会按locale用逗号分割

'('                            负数结果会被括号括起


更详细的资料能够看JDK文档

http://docs.oracle.com/javase/1.5.0/docs/api/java/util/Formatter.html

相关文章
相关标签/搜索