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

JDK 5 新特性:printf 風格格式化輸出完整指南

     編輯:Java 相關知識

核心 API

JDK 5 在 PrintStream、PrintWriter、String 中新增四個格式化方法:

  • format(String fmt, Object... args)
  • printf(String fmt, Object... args) (format 同義)
  • format(Locale loc, String fmt, Object... args)
  • printf(Locale loc, String fmt, Object... args)

Formatter 類提供更底層的控制,支援 StringBuilder 緩衝區。

格式化語法詳解

%[argument_index$][flags][width][.precision]conversion

元素說明範例
argument_index參數索引 (1-based),%1$ 表示第一個參數%1$d %1$d 重複使用
flags'-' 左對齊, '+' 正負號, '0' 補零, ',' 千分位, '(' 負數括號%,.2f
width最小字元寬度%10d
precision小數位數或字串最大長度%.2f
conversion類型轉換字元見下表

常用轉換字元

字元類型說明
d整數十進制
f浮點數十進制浮點
e浮點數科學記號
x整數十六進制小寫
s任意字串 (toString())
c字元Unicode 字元
t日期/時間需搭配後綴 (見下)
b布林true/false
%-輸出 '%'
n-平台相關換行符

日期/時間後綴 (搭配 t)

  • tR - 24小時制 HH:MM
  • tA - 完整星期名
  • tB - 完整月份名
  • te - 月份中的日期 (1-31)
  • tY - 四位年份
  • < - 復用前一個參數 (避免重複傳遞)

實戰範例

基本數值格式化

System.out.printf("Pi = %.2f, e = %.4f%n", Math.PI, Math.E);
// Pi = 3.14, e = 2.7183

參數索引與復用

formatter.format("Pi = %1$.2f, e = %2$.2f, Pi again = %1$.2f", Math.PI, Math.E);
// Pi = 3.14, e = 2.72, Pi again = 3.14

日期時間格式化

Calendar now = Calendar.getInstance();
System.out.printf("Now: %tR on %tA, %tB %te, %tY%n", now, now, now, now, now);
// 使用 < 簡化
System.out.printf("Now: %tR on %<tA, %<tB %<te, %<tY%n", now);

Locale 敏感格式化

Formatter f = new Formatter(sb, Locale.FRANCE);
f.format("Pi = %.2f", Math.PI); // 輸出 "Pi = 3,14" (法文逗號分隔)

Formatter 進階用法

StringBuilder sb = new StringBuilder();
Formatter formatter = new Formatter(sb);
formatter.format("User: %s, Age: %d, Active: %b", "Alice", 30, true);
System.out.println(sb.toString());

總結

JDK 5 的格式化 API 將 C 風格 printf 的強大功能引入 Java,支援型別安全、Locale 敏感、參數復用與靈活的輸出目標,是取代繁瑣字串串接的最佳選擇。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved