目录
- printf()/format()方法
- Formatter类
printf()/format()方法
Java 继SE5之后,推出了C语言中printf()风格的格式化输出,这对于以前玩C的有种莫名的熟悉感。
java中printf函数支持以下类型形式:
| 标识符 | 含义 |
|---|---|
| %c | 输出单个字符 |
| %d | 十进制整数 |
| %f | 十进制浮点数 |
| %s | 字符串 |
| %b | boolean类型 |
| %o | 八进制 |
| %x | 十六进制 |
| %% | 仅输出百分号% |
输出示例:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 | public class PrintfDemo { public static void main(String[] args) { //整数型 byte b=2; short s=22; int i=12; long l=22; //浮点型 float f=1.1111f; double d=111.1111; //字符型 char c='A'; //字符串型 String str="hello world"; System.out.println("============================"); System.out.printf("基本数据类型使用printf()格式化输出:\n"); System.out.printf("整数型:byte:%d\tshort:%d\tint:%d\tlong:%d\n",b,s,i,l); System.out.printf("浮点型:float:%f\tdouble:%f\n",f,d); System.out.printf("字符型:char:%c\n",c); System.out.printf("字符串:String:%s\n",str); System.out.printf("int:%x\n",i); System.out.printf("int:%o\n",i-8); System.out.printf("98.99%%\n"); } } |
运行样例:
Java中格式规范:
| 标识符 | 含义 |
|---|---|
| % | 使用printf函数规范输入的标志性符号,不可缺少。 |
| %-d | ‘-’表示输出左端对齐,省略则右对齐。 |
| %Md | M表示整型的域宽。如M过大,用空格替代。 |
| %.Nf | N表示小数点后的数字个数。如N过大,用0替代。 |
| %M.Nf | M表示对整个浮点型的宽度,N表示浮点型小数点后面数字的个数。如M过小,N过大,则会默认将浮点型完整输出。 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | public class PrintfDemo { public static void main(String[] args) { //整数型 byte b=2; short s=22; int i=12; long l=22; //浮点型 float f=1.1111f; double d=111.1111; //字符型 char c='A'; //字符串型 String str="hello world"; System.out.println("============================"); System.out.printf("基本数据类型使用printf()格式化输出:\n"); System.out.printf("整数型:byte:%d\tshort:%d\tint:%d\tlong:%d\n",b,s,i,l); System.out.printf("浮点型:float:%f\tdouble:%f\n",f,d); System.out.printf("字符型:char:%c\n",c); System.out.printf("字符串:String:%s\n",str); System.out.printf("int:%x\n",i); System.out.printf("int:%o\n",i-8); System.out.printf("98.99%%\n"); System.out.println("============================"); //printf()的特殊用法 System.out.println("对于printf()的特殊用法:"); System.out.printf("int:%4d\n",i); System.out.printf("int:%-4d\n",i); System.out.printf("float:%.2f\n",f); System.out.printf("double:%12.7f\n",d); } } |
运行样例:

Formatter类
一般来说,所有新的格式化功能均由Formatter类处理。该类将自定义格式化字符串与数据结合,实现规范化。值得注意的是初始化Formatter类时,需要向其构造器传递参数,该参数表示规范化的结果输出位置。
示例:
1 2 3 4 5 6 7 8 9 | public class FormatterDemo { public static void main(String[] args) { int i = 1, j = 2; Formatter f = new Formatter(System.out); f.format("%d + 1 = %d\n", i, j); String str = "1221212"; System.out.println(String.format("q+%s",str)); } } |
运行样例:

在上述代码中,使用了String.format()方法,该方法是一个static方法,其内部也封装了Formatter对象。
个人建议,对于粗糙的规范化数据,直接用printf()或者String.format()封装好的就行,不用重新造轮子。