Java 5 以前拼接字串只能用 +,既醜陋又難對齊。printf、format、Formatter、String.format 提供了 C 風格的強大格式化能力。
int x = 5; double y = 3.141592;
// 1. PrintStream.printf (最常用)
System.out.printf("x = %d, y = %f%n", x, y);
// 2. PrintStream.format (printf 內部調用它)
System.out.format("x = %d, y = %f%n", x, y);
// 3. String.format (返回字串,不直接輸出)
String s = String.format("x = %d, y = %f", x, y);
System.out.println(s);
// 輸出均為: x = 5, y = 3.141592
所有格式化最終委派給 java.util.Formatter。可指定輸出目標 (輸出流、文件、StringBuilder)。
StringBuilder sb = new StringBuilder();
Formatter fmt = new Formatter(sb);
fmt.format("Name: %s, Age: %d", "huhx", 22);
fmt.close(); // 釋放資源
System.out.println(sb); // Name: huhx, Age: 22
%[argument_index$][flags][width][.precision]conversion
| 組件 | 說明 | 範例 |
|---|---|---|
argument_index$ | 參數索引 (1-based),支持重複使用參數 | %1$s %1$d |
flags | 修飾輸出格式 | -左對齊 +正數顯示+ 0前導零 ,千分位 (負數括號 |
width | 最小字符寬度,不足補空格 (默認右對齊) | %10d |
.precision | 最大精度:字串截取長度 / 浮點數小數位 | %.2f %.5s |
conversion | 轉換類型 (必須) | 見下表 |
| 字符 | 含義 | 適用類型 | 範例輸出 |
|---|---|---|---|
d | 十進制整數 | int, long, Byte, Short, Integer, Long | 123 |
f | 十進制浮點數 | float, double, Float, Double | 3.14 |
e | 科學計數法 | float, double | 3.14e+00 |
x | 十六進制整數 (小寫) | 整數類型 | 7b |
s | 字串 | 任意對象 (調用 toString) | hello |
c | Unicode 字符 | char, Character, int | A |
b | 布爾值 | Boolean, 任意 (非 null 為 true) | true |
h | 哈希碼十六進制 | 任意對象 | 1a2b3c |
% | 字面值 % | — | % |
n | 平台相關換行符 | — | \n 或 \r\n |
Formatter f = new Formatter(System.out);
// %-15s : 左對齊,寬度15
// %5d : 右對齊,寬度5
// %10.2f: 右對齊,寬度10,保留2位小數
f.format("%-15s %5s %10s%n", "Name", "Age", "Score");
f.format("%-15s %5d %10.2f%n", "Alice", 20, 92.5);
f.format("%-15s %5d %10.2f%n", "Bob", 22, 85.0);
f.close();
Name Age Score Alice 20 92.50 Bob 22 85.00
%.4s 只取前 4 字符。%.2f 保留 2 位小數 (四捨五入/補零)。IllegalFormatPrecisionException。
public class HexDump {
public static String format(byte[] data) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < data.length; i++) {
if (i % 16 == 0) {
sb.append(String.format("%05x: ", i)); // 偏移地址
}
sb.append(String.format("%02x ", data[i])); // 字節值
if (i % 16 == 15 || i == data.length - 1) {
sb.append("\n");
}
}
return sb.toString();
}
public static void main(String[] args) {
String s = "my name is huhx, welcome to my blog";
System.out.println(format(s.getBytes()));
}
}
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
System.out.printf / String.format,代碼簡潔。Formatter。% 需轉義為 %%,換行用 %n 而非 \n 以保跨平台。