Java基礎掃盲系列(-)—— String中的format


Java基礎掃盲系列(-)—— String中的format

以前大學學習C語言時,有函數printf,能夠按照格式打印輸出的內容。但是工作后使用Java,也沒有遇到過格式打印的需求,今天遇到項目代碼使用String.format()工具api。

這里完善知識體系,將Java中的formatter簡單的總結下。

An interpreter for printf-style format strings. This class provides support for layout justification and alignment, common formats for numeric, string, and date/time data, and locale-specific output. Common Java types such as {@code byte}, {@link java.math.BigDecimal BigDecimal}, and {@link Calendar} are supported. Limited formatting customization for arbitrary user types is provided through the {@link Formattable} interface.

Java docs中是這樣描述Formatter的:

格式化打印字符串的攔截器。Formatter提供對布局和對齊,格式化數值、字符串、日期時間和特定的本地化輸出的能力。甚至連常用的BigDecimal,Calendar,byte類型都提供了支持。

先來看下簡單的例子,認識下Formatter的格式能力:

int a = 1;
int b = 100;

System.out.println(String.format("%03d", a));
System.out.println(String.format("%03d", b));

輸出結果:

001
100

大致可以看出formatter的能力了吧。將參數按照設定的格式進行格式化。

Formatter是Java SE 5提供的api,就是為了對格式化提供支撐。常用的字符和數值類型的格式化語法如下:

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

  • argument_index$可選參數,用來按照位置指定參數,1$表示第一個參數;
  • flags是可選參數,是一個字符集用來控制輸出格式,依賴后面的轉換conversion;
  • width可選參數,是一個非負的整型,用來控制輸出的字符個數;
  • precision可選參數,是一個非負整型,用來控制小數點后的個數;
  • conversion必選,是一個字符,用來表示參數怎樣被格式化;

對於各個參數想詳細信息和日期時間,甚至其功能的格式化(大小寫轉換),請參考api文檔: Class Formatter

在Java字節的類庫中也有大量使用Formatter的痕跡:

  • String類提供的靜態api

      public static String format(String format, Object... args) {
      	return new Formatter().format(format, args).toString();
      }
    
  • System.out.printf():

      public PrintStream printf(String format, Object ... args) {
      	return format(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的格式化能力包裝后提供的簡潔api。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM