Java的格式化輸出

java基礎---->Java的格式化輸出

 

  在JavaSe5中,推出了C語言中printf()風格的格式化輸出。這不只使得控制輸出的代碼更加簡單,同時也給與Java開發者對於輸出格式與排列更大的控制能力。今天,咱們開始學習Java中的格式化輸出。html

 

目錄導航java

  1.   System.out.format()
  2.   Formatter類
  3.   格式化說明符
  4.   Formatter轉換
  5.   簡單的十六進制轉換工具
  6.   友情連接

 

System.out.format()

因爲內容比較簡單,咱們經過實例來加以說明。項目結構以下:linux

Java Se5引入的format方法可用於PrintStream或PrintWriter對象,其中也包括System.out對象。app

複製代碼
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);
    }
}
複製代碼

輸出的結果以下:工具

x = 5, y = 3.141592
x = 5, y = 3.141592
x = 5, y = 3.141592

能夠看到,format與printf是等價的,它們只須要一個簡單的格式化字符串,加上一串參數便可,每一個參數對應一個格式修飾符。post

public PrintStream printf(String format, Object ... args) {
    return format(format, args);
}

 在format的具體代碼中,其實就是調用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看做是一個翻譯器,它將你的格式化字符串與數據翻譯成須要的結果。當你建立一個Formatter對象的時候 ,須要向其構造器傳遞一些信息,告訴它最終的結果將向哪裏輸出ui

複製代碼
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();
    }
}
複製代碼

它的輸出結果以下:this

My name is huhx, and my age is 22 

 

格式化說明符

在插入數據時,若是想要控制空格與對齊,就須要精細複雜的格式修飾符,如下是其抽象的語法:url

複製代碼
%[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.
複製代碼

 最多見的應用是控制一個域的最小尺寸,這能夠經過指定width來實現。Formatter對象經過在必要時添加空格,來確保一個域至少達到某個長度。在默認的狀況下,數據是右對齊的,經過"-"標誌能夠改變對齊的方向。

與width相對的是precision(精確度),它用來指明最大尺寸。width能夠應用各類類型的數據轉換,而且其行爲方式都同樣。precision則不同,不是全部類型的數據都能使用precision,並且,應用於不一樣的類型的數據轉換時,precision的意義也不一樣。

  • precision應用於String時,它表示打印String時輸出字符的最大數量
  • precision應用於浮點數時,它表示小數點要顯示出來的位數。默認是6位小數,若是小數位數過多則舍入,過少則在尾部補零。
  • 因爲整數沒有小數部分,因此precision不能應用於整數。若是你對整數應用precision,則會觸發異常
複製代碼
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();
    }
}
複製代碼

它的輸出結果以下:

huhx            linux liuli     
zhangkun        yanzi zhangcong 
zhangkun        yanzhou zhangcong 
----------------------------
My name is huhx     5       4.20
My n                5       4.10

 

Formatter轉換

 下面的表格包含了最經常使用的類型轉換:

類型轉換字符
d 整數型(10進制 ) e 浮點數(科學計數)
c Unicode字符 x 整數(16進制)
b Boolean值 h 散列碼(16進制)
s String % 字符"%"
f 浮點數(10進制)    

String.format()是一個static方法,它接受與Formatter.format()方法同樣的參數,但返回一個String對象。當你只須要用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);
    }
}
複製代碼

它的輸出結果以下:

My name is huhx and my age is 22

其實String.format方法的實質仍是Formatter.format(),只不過是作了簡單封裝而已:

public static String format(String format, Object... args) {
    return new Formatter().format(format, args).toString();
}

 

簡單的十六進制轉換工具

複製代碼
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()));
    }
}
複製代碼

輸出結果以下:

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 

 

友情連接

 

做者:  huhx 
出處:  www.cnblogs.com/huhx
格言:你盡力了,纔有資格說本身的運氣很差。
版權:本文版權歸做者huhx和博客園共有,歡迎轉載。未經做者贊成必須保留此段聲明,且在文章頁面明顯位置給出原文連接,不然保留追究法律責任的權利。
原文請看:https://www.cnblogs.com/huhx/p/javaFormatter.html
相關文章
相關標籤/搜索