Java之格式化輸出實(shí)踐
在JavaSe5中,推出了C語言中printf()風(fēng)格的格式化輸出。這不僅使得控制輸出的代碼更加簡單,同時也給與Java開發(fā)者對于輸出格式與排列更大的控制能力。
今天,我們開始學(xué)習(xí)Java中的格式化輸出。
System.out.format()
由于內(nèi)容比較簡單,我們通過實(shí)例來加以說明。項(xiàng)目結(jié)構(gòu)如下:

Java Se5引入的format方法可用于PrintStream或PrintWriter對象,其中也包括System.out對象。
package com.tomhu.format;
public class FormatTest1 {
public static void main(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);
}
}輸出的結(jié)果如下:
x = 5,
y = 3.141592x = 5,
y = 3.141592x = 5,
y = 3.141592
可以看到,format與printf是等價的,它們只需要一個簡單的格式化字符串,加上一串參數(shù)即可,每個參數(shù)對應(yīng)一個格式修飾符。
public PrintStream printf(String format, Object ... args) {
return format(format, args);
}在format的具體代碼中,其實(shí)就是調(diào)用Formatter的format方法:formatter.format(Locale.getDefault(), format, args);
public PrintStream 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看作是一個翻譯器,它將你的格式化字符串與數(shù)據(jù)翻譯成需要的結(jié)果。
當(dāng)你創(chuàng)建一個Formatter對象的時候 ,需要向其構(gòu)造器傳遞一些信息,告訴它最終的結(jié)果將向哪里輸出
package com.tomhu.format;import java.util.Formatter;public class FormatTest2 {
public static void main(String[] args) {
String name = "huhx";
int age = 22;
Formatter formatter = new Formatter(System.out);
formatter.format("My name is %s, and my age is %d ", name, age);
formatter.close();
}
}它的輸出結(jié)果如下:
My name is huhx, and my age is 22
格式化說明符
在插入數(shù)據(jù)時,如果想要控制空格與對齊,就需要精細(xì)復(fù)雜的格式修飾符,以下是其抽象的語法:
%[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 conversions for a given argument depends on the argument's data type.
最常見的應(yīng)用是控制一個域的最小尺寸,這可以通過指定width來實(shí)現(xiàn)。Formatter對象通過在必要時添加空格,來確保一個域至少達(dá)到某個長度。在默認(rèn)的情況下,數(shù)據(jù)是右對齊的,通過"-"標(biāo)志可以改變對齊的方向。
與width相對的是precision(精確度),它用來指明最大尺寸。width可以應(yīng)用各種類型的數(shù)據(jù)轉(zhuǎn)換,并且其行為方式都一樣。precision則不一樣,不是所有類型的數(shù)據(jù)都能使用precision,而且,應(yīng)用于不同的類型的數(shù)據(jù)轉(zhuǎn)換時,precision的意義也不同。
1.precision應(yīng)用于String時,它表示打印String時輸出字符的最大數(shù)量
2.precision應(yīng)用于浮點(diǎn)數(shù)時,它表示小數(shù)點(diǎn)要顯示出來的位數(shù)。默認(rèn)是6位小數(shù),如果小數(shù)位數(shù)過多則舍入,過少則在尾部補(bǔ)零。
3.由于整數(shù)沒有小數(shù)部分,所以precision不能應(yīng)用于整數(shù)。如果你對整數(shù)應(yīng)用precision,則會觸發(fā)異常
package com.tomhu.format;import java.util.Formatter;public class FormatTest3 {
static Formatter formatter = new Formatter(System.out);
public static void printTitle() {
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 void print() {
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 void main(String[] args) {
printTitle();
System.out.println("----------------------------");
print();
formatter.close();
}
}它的輸出結(jié)果如下:
huhx linux liuli
zhangkun yanzi zhangcong
zhangkun yanzhou zhangcong
----------------------------
My name is huhx 5 4.20
My n 5 4.10
Formatter轉(zhuǎn)換
下圖包含了最常用的類型轉(zhuǎn)換:

String.format()是一個static方法,它接受與Formatter.format()方法一樣的參數(shù),但返回一個String對象。
當(dāng)你只需要用format方法一次的時候,String.format()還是很方便的。
package com.tomhu.format;
public class FormatTest4 {
public static void main(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);
}
}它的輸出結(jié)果如下:
My name is huhx and my age is 22
其實(shí)String.format方法的實(shí)質(zhì)還是Formatter.format(),只不過是做了簡單封裝而已:
public static String format(String format, Object... args) {
return new Formatter().format(format, args).toString();
}簡單的十六進(jìn)制轉(zhuǎn)換工具
package com.tomhu.format;
public class FormatTest5 {
public static String format(byte[] data) {
StringBuilder builder = new StringBuilder();
int n = 0;
for(byte b: 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");
return builder.toString();
}
public static void main(String[] args) {
String string = "my name is huhx, welcome to my blog";
System.out.println(format(string.getBytes()));
}
}輸出結(jié)果如下:
00000: 6d 79 20 6e 61 6d 65 20 69 73 20 68 75 68 78 2c
00010: 20 77 65 6c 63 6f 6d 65 20 74 6f 20 6d 79 20 62
00020: 6c 6f 67
總結(jié)
以上為個人經(jīng)驗(yàn),希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
JavaMail發(fā)送(帶圖片和附件)和接收郵件實(shí)現(xiàn)詳解(四)
這篇文章主要為大家詳細(xì)介紹了JavaMail帶圖片和附件的發(fā)送和接收郵件實(shí)現(xiàn),具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10
利用IDEA社區(qū)版創(chuàng)建SpringBoot項(xiàng)目的詳細(xì)圖文教程
大家應(yīng)該都知道Idea社區(qū)版本,默認(rèn)是不能創(chuàng)建SpringBoot項(xiàng)目的,下面這篇文章主要給大家介紹了關(guān)于利用IDEA社區(qū)版創(chuàng)建SpringBoot項(xiàng)目的詳細(xì)圖文教程,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-04-04
Java?Spring?boot?配置JDK和MAVEN開發(fā)環(huán)境的過程
本文詳細(xì)介紹了如何配置JDK和Maven環(huán)境,包括JDK的安裝與環(huán)境變量設(shè)置,Maven的下載、配置環(huán)境變量和設(shè)置阿里云倉庫,最后簡述了在IntelliJ?IDEA中配置JDK和Maven的步驟,本教程適合Java開發(fā)新手進(jìn)行開發(fā)環(huán)境的搭建,確保順利進(jìn)行Java項(xiàng)目的開發(fā)2024-11-11
詳解Spring mvc DispatchServlet 實(shí)現(xiàn)機(jī)制
本篇文章主要介紹了詳解Spring mvc DispatchServlet 實(shí)現(xiàn)機(jī)制,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-09-09
Java類中this關(guān)鍵字與static關(guān)鍵字的用法解析
這篇文章主要介紹了Java類中this關(guān)鍵字與static關(guān)鍵字的用法解析,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09
idea中提示Class 'xxx' is never us
這篇文章主要介紹了idea中提示Class 'xxx' is never used的解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01

