首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 程式設計入門

Java 格式化輸出完全指南:printf、Formatter、String.format 與十六進制工具實戰

     編輯:Java 程式設計入門

Java 5 引入的格式化家族

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

Formatter 類:底層引擎

所有格式化最終委派給 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, Long123
f十進制浮點數float, double, Float, Double3.14
e科學計數法float, double3.14e+00
x十六進制整數 (小寫)整數類型7b
s字串任意對象 (調用 toString)hello
cUnicode 字符char, Character, intA
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

精度對不同類型的差異行為

  • String:%.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 

最佳實踐建議

  1. 優先使用 System.out.printf / String.format,代碼簡潔。
  2. 需重複使用格式器或輸出到非標準流時,直接用 Formatter。
  3. 對齊報表、日誌固定寬度字段、網絡協議構造、十六進制調試 —— 格式化是首選。
  4. 注意 % 需轉義為 %%,換行用 %n 而非 \n 以保跨平台。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved