java基础---->Java的格式化输出

在JavaSe5中,推出了C语言中printf()风格的格式化输出。这不仅使得控制输出的代码更加简单,同时也给与Java开发者对于输出格式与排列更大的控制能力。今天,我们开始学习Java中的格式化输出。

System.out.format()
由于内容比较简单,我们通过实例来加以说明。项目结构如下:

1.12.11.png

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

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是等价的,它们只需要一个简单的格式化字符串,加上一串参数即可,每个参数对应一个格式修饰符。

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对象的时候 ,需要向其构造器传递一些信息,告诉它最终的结果将向哪里输出

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();
    }
}

它的输出结果如下:

My name is huhx, and my age is 22 

格式化说明符
在插入数据时,如果想要控制空格与对齐,就需要精细复杂的格式修饰符,以下是其抽象的语法:

%[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转换
下面的表格包含了最常用的类型转换:

[图片上传失败...(image-2c3f72-1610463782036)]

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 

image

最新2020整理收集的一些高频面试题(都整理成文档),有很多干货,包含mysql,netty,spring,线程,spring cloud、jvm、源码、算法等详细讲解,也有详细的学习规划图,面试题整理等,需要获取这些内容的朋友请加Q君样:909038429
/./*欢迎加入java交流Q君样:909038429一起吹水聊天

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,036评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,046评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,411评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,622评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,661评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,521评论 1 304
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,288评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,200评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,644评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,837评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,953评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,673评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,281评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,889评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,011评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,119评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,901评论 2 355

推荐阅读更多精彩内容