输出java_java基础----Java的格式化输出
在JavaSe5中,推出了C语言中printf()风格的格式化输出。这不仅使得控制输出的代码更加简单,同时也给与Java开发者对于输出格式与排列更大的控制能力。今天,我们开始学习Java中的格式化输出。
目录导航
System.out.format()
由于内容比较简单,我们通过实例来加以说明。项目结构如下:
Java Se5引入的format方法可用于PrintStream或PrintWriter对象,其中也包括System.out对象。
packagecom.tomhu.format;public classFormatTest1 {public static voidmain(String[] args) {int x = 5;double y = 3.141592;//一般方式
System.out.println("x = " + x + ", y = " +y);//printf()方式
System.out.printf("x = %d, y = %f\n", x, y);//format()方式
System.out.format("x = %d, y = %f\n", x, y);
}
}
输出的结果如下:
x = 5, y = 3.141592x= 5, y = 3.141592x= 5, y = 3.141592
可以看到,format与printf是等价的,它们只需要一个简单的格式化字符串,加上一串参数即可,每个参数对应一个格式修饰符。
publicPrintStream printf(String format, Object ... args) {returnformat(format, args);
}
在format的具体代码中,其实就是调用Formatter的format方法:formatter.format(Locale.getDefault(), format, args);
publicPrintStream format(String format, Object ... args) {try{synchronized (this) {
ensureOpen();if ((formatter == null)|| (formatter.locale() !=Locale.getDefault()))
formatter= new Formatter((Appendable) this);
formatter.format(Locale.getDefault(), format, args);
}
}catch(InterruptedIOException x) {
Thread.currentThread().interrupt();
}catch(IOException x) {
trouble= true;
}return this;
}
Formatter类
在Java中,所有新的格式化功能都由Formatter类处理,上述的printf与format也是。可以将Formatter看作是一个翻译器,它将你的格式化字符串与数据翻译成需要的结果。当你创建一个Formatter对象的时候 ,需要向其构造器传递一些信息,告诉它最终的结果将向哪里输出
packagecom.tomhu.format;importjava.util.Formatter;public classFormatTest2 {public static voidmain(String[] args) {
String name= "huhx";int age = 22;
Formatter formatter= newFormatter(System.out);
formatter.format("My name is %s, and my age is %d ", name, age);
formatter.close();
}
}
它的输出结果如下:
My name is huhx, and my age is 22
格式化说明符
在插入数据时,如果想要控制空格与对齐,就需要精细复杂的格式修饰符,以下是其抽象的语法:
%[argument_index$][flags][width][.precision]conversion
The optional argument_index is a decimal integer indicating the position of the argument in the argument list. The first argument is referenced by"1$", the second by "2$", etc.
The optional flags is a set of characters that modify the output format. The set of valid flags depends on the conversion.
The optional width is a non-negative decimal integer indicating the minimum number of characters to be written to the output.
The optional precision is a non-negative decimal integer usually used to restrict the number of characters. The specific behavior depends on the conversion.
The required conversion is a character indicating how the argument should be formatted. The set of valid conversionsfor a given argument depends on the argument's data type.
最常见的应用是控制一个域的最小尺寸,这可以通过指定width来实现。Formatter对象通过在必要时添加空格,来确保一个域至少达到某个长度。在默认的情况下,数据是右对齐的,通过"-"标志可以改变对齐的方向。
与width相对的是precision(精确度),它用来指明最大尺寸。width可以应用各种类型的数据转换,并且其行为方式都一样。precision则不一样,不是所有类型的数据都能使用precision,而且,应用于不同的类型的数据转换时,precision的意义也不同。
precision应用于String时,它表示打印String时输出字符的最大数量
precision应用于浮点数时,它表示小数点要显示出来的位数。默认是6位小数,如果小数位数过多则舍入,过少则在尾部补零。
由于整数没有小数部分,所以precision不能应用于整数。如果你对整数应用precision,则会触发异常
packagecom.tomhu.format;importjava.util.Formatter;public classFormatTest3 {static Formatter formatter = newFormatter(System.out);public static voidprintTitle() {
formatter.format("%-15s %-5s %-10s\n", "huhx", "linux", "liuli");
formatter.format("%-15s %-5s %-10s\n", "zhangkun", "yanzi", "zhangcong");
formatter.format("%-15s %-5s %-10s\n", "zhangkun", "yanzhou", "zhangcong");
}public static voidprint() {
formatter.format("%-15s %5d %10.2f\n", "My name is huhx", 5, 4.2);
formatter.format("%-15.4s %5d %10.2f\n", "My name is huhx", 5, 4.1);
}public static voidmain(String[] args) {
printTitle();
System.out.println("----------------------------");
print();
formatter.close();
}
}
它的输出结果如下:
huhx linux liuli
zhangkun yanzi zhangcong
zhangkun yanzhou zhangcong----------------------------My name is huhx5 4.20My n5 4.10
Formatter转换
下面的表格包含了最常用的类型转换:
类型转换字符
d
整数型(10进制 )
e
浮点数(科学计数)
c
Unicode字符
x
整数(16进制)
b
Boolean值
h
散列码(16进制)
s
String
%
字符"%"
f
浮点数(10进制)
String.format()是一个static方法,它接受与Formatter.format()方法一样的参数,但返回一个String对象。当你只需要用format方法一次的时候,String.format()还是很方便的。
packagecom.tomhu.format;public classFormatTest4 {public static voidmain(String[] args) {int age = 22;
String name= "huhx";
String info= String.format("My name is %s and my age is %d", name, age);
System.out.println(info);
}
}
它的输出结果如下:
My name is huhx and my age is 22
其实String.format方法的实质还是Formatter.format(),只不过是做了简单封装而已:
public staticString format(String format, Object... args) {return newFormatter().format(format, args).toString();
}
简单的十六进制转换工具
packagecom.tomhu.format;public classFormatTest5 {public static String format(byte[] data) {
StringBuilder builder= newStringBuilder();int n = 0;for(byteb: data) {if (n %16 == 0) {
builder.append(String.format("%05x: ", n));
}
builder.append(String.format("%02x ", b));
n++;if (n % 16 == 0) {
builder.append("\n");
}
}
builder.append("\n");returnbuilder.toString();
}public static voidmain(String[] args) {
String string= "my name is huhx, welcome to my blog";
System.out.println(format(string.getBytes()));
}
}
输出结果如下:
00000: 6d 79 20 6e 61 6d 65 20 69 73 20 68 75 68 782c00010: 20 77 65 6c 63 6f 6d 65 20 74 6f 20 6d 79 20 62
00020: 6c 6f 67
友情链接
输出java_java基础----Java的格式化输出相关推荐
- java基础----Java的格式化输出
在JavaSe5中,推出了C语言中printf()风格的格式化输出.这不仅使得控制输出的代码更加简单,同时也给与Java开发者对于输出格式与排列更大的控制能力.今天,我们开始学习Java中的格式化输出 ...
- php输出json html,html怎样格式化输出JSON数据
这次给大家带来html怎样格式化输出JSON数据,html格式化输出JSON数据的注意事项有哪些,下面就是实战案例,一起来看一下. 将 json 数据以美观的缩进格式显示出来,借助最简单的 JSON. ...
- python编程格式化输出_Python的三种格式化输出
今天刚学了python的三种格式化输出,以前没接触过这么有趣的输出方式,现在来分享一下. #!/user/bin/env python #coding:utf-8 #三种格式化输出 #第一种格式化输出 ...
- c++ 输出二进制_Python入门3print格式化输出的几种方法
接<Python入门2> print格式化输出的几种方法 ⒂格式化输出举例 [例] str_name="小明" num_age=15 print("我叫%s, ...
- Java如何格式化输出?
在JavaSe5中,推出了C语言中printf()风格的格式化输出.这不仅使得控制输出的代码更加简单,同时也给与Java开发者对于输出格式与排列更大的控制能力.今天,我们开始学习Java中的格式化输出 ...
- java print 格式化输出_java 格式化输出方法
在javaSE5中推出了printf方法来输出文本到控制台,在java中现在有如下方法可以输出文本: 1.System.out.println(....) //输出并换行 2.System.out.f ...
- 【Python学习笔记】第一章基础知识:格式化输出,转义字符,变量类型转换,算术运算符,运算符优先级和赋值运算符,逻辑运算符,世界杯案例题目,条件判断if语句,猜拳游戏与三目运算符
Python学习笔记之[第一章]基础知识 前言: 一.格式化输出 1.基本格式: 2.练习代码: 二.转义字符 1.基本格式: 2.练习代码: 3.输出结果: 三.输入 1.基本格式: 2.练习代码: ...
- java date格式化输出_Java Date类以及日期的格式化输出
Java中的Date类用于表示日期时间,在java.util包中.虽然Date类在设计之初没有考虑到国际化,很多方法都已经被定义为过时,但是Date却是程序设计过程中经常用到的一个类.本文将说说Dat ...
- Java中格式化输出
文章目录 一.要点提示 二.常用的格式标识符 三.格式标识符的解释 四.指定宽度和精度的例子 五.格式化输出语法 六.注意的问题 七.应用 一.要点提示 在控制台上显示格式化输出:System.out ...
最新文章
- 一包烟钱买到电动剃须刀,小米有品告诉你什么叫性价比
- 身份证号码有效性检测算法 ( js版 转 .net版 )
- 12 Useful Tips for Machine Learning (转载)
- VTK:图表之ColorVertexLabels
- Web游戏开发编程:最神奇的“触觉振动”
- exec函数族实例解析
- 去大厂也就图一乐,真人上人还得是外包
- [bzoj1500 维修数列](NOI2005) (splay)
- 电厂运维的cis数据_科技驱动升级,各类智慧电厂技术大盘点
- shopnum1商城系统
- BGP路径属性分类与实验(华为设备)
- ios开发之 -- 强制横屏
- DeskPins v1.32 绿色汉化版
- Word转PDF怎么转?三种方法快速学会
- TMB计算是否要去除驱动突变
- 借助抖音节点营销 佳沛打开“金九”新局面
- 谷歌学术上不了的解决办法
- win10蓝牙链接上的标准串行com口无法删除
- 学习周记1:2019.2.18-2019.2.24
- 关于傅立叶系数的计算公式
热门文章
- [云炬创业基础笔记]第五章创业机会评估测试6
- [云炬学英语]每日一句2020.9.1
- 云炬随笔20190301
- 3DSlicer16:数据类型MRML
- 结构张量用于区分平坦、边缘、角点区域
- 【MFC】1.Windows程序内部运行原理
- xp,win7,win2003,win2008常用命令集
- 利用Sql Server2005发送邮件
- PL0编译器TurboPascal版再现时间:2009-07-20 17:24:49来源:网络 作者:未知 点击:52次
- 一步一步的写出你自己的makefile文件