标签:
java.util.Formatter是JDK1.5新增的类,支持类似C中的printf风格的字符串格式化工作
Formatter有4个构造方法,如下:
public Formatter()
public Formatter(Appendable a)
public Formatter(Locale l)
public Formatter(Appendable a, Locale l)
构造方法主要用于设置Formatter的缓冲器和Locale,默认的情况下,Formatter使用StringBuilder作为缓冲器,使用Locale.getDefault()作为locale。
Formatter的使用方法如下(摘自JDK DOC):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方法取出。
更为一般的用法是使用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文档
标签: