• 十八、字符串(2)


    本章概要

    • 格式化输出
      • printf()
      • Systen.out.format()
      • Formatter 类
      • 格式化修饰符
      • Formatter 转换
      • String.format()
        • 一个十六进制转储(dump)工具

    格式化输出

    在长久的等待之后,Java SE5 终于推出了 C 语言中 printf() 风格的格式化输出这一功能。这不仅使得控制输出的代码更加简单,同时也给与Java开发者对于输出格式与排列更强大的控制能力。

    printf()

    C 语言的 printf() 并不像 Java 那样连接字符串,它使用一个简单的格式化字符串,加上要插入其中的值,然后将其格式化输出。 printf() 并不使用重载的 + 操作符(C语言没有重载)来连接引号内的字符串或字符串变量,而是使用特殊的占位符来表示数据将来的位置。而且它还将插入格式化字符串的参数,以逗号分隔,排成一行。例如:

    System.out.printf("Row 1: [%d %f]%n", x, y);
    
    • 1

    这一行代码在运行的时候,首先将 x 的值插入到 %d_ 的位置,然后将 y 的值插入到 %f 的位置。这些占位符叫做_格式修饰符_,它们不仅指明了插入数据的位置,同时还指明了将会插入什么类型的变量,以及如何格式化。在这个例子中 %d 表示 x 是一个整数,%f 表示 y 是一个浮点数(float 或者 double)。

    System.out.format()

    Java SE5 引入了 format() 方法,可用于 PrintStream 或者 PrintWriter 对象,其中也包括 System.out 对象。format() 方法模仿了 C 语言的 printf()。如果你比较怀旧的话,也可以使用 printf()。以下是一个简单的示例:

    public class SimpleFormat {
        public static void main(String[] args) {
            int x = 5;
            double y = 5.332542;
            // The old way: 
            System.out.println("Row 1: [" + x + " " + y + "]");
            // The new way:     
            System.out.format("Row 1: [%d %f]%n", x, y);
            // or     
            System.out.printf("Row 1: [%d %f]%n", x, y);
        }
    } 
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    在这里插入图片描述

    可以看到,format()printf() 是等价的,它们只需要一个简单的格式化字符串,加上一串参数即可,每个参数对应一个格式修饰符。

    String 类也有一个 static format() 方法,可以格式化字符串。

    Formatter

    在 Java 中,所有的格式化功能都是由 java.util.Formatter 类处理的。可以将 Formatter 看做一个翻译器,它将你的格式化字符串与数据翻译成需要的结果。当你创建一个 Formatter 对象时,需要向其构造器传递一些信息,告诉它最终的结果将向哪里输出:

    import java.io.*;
    import java.util.*;
    
    public class Turtle {
        private String name;
        private Formatter f;
    
        public Turtle(String name, Formatter f) {
            this.name = name;
            this.f = f;
        }
    
        public void move(int x, int y) {
            f.format("%s The Turtle is at (%d,%d)%n",
                    name, x, y);
        }
    
        public static void main(String[] args) {
            PrintStream outAlias = System.out;
            Turtle tommy = new Turtle("Tommy",
                    new Formatter(System.out));
            Turtle terry = new Turtle("Terry",
                    new Formatter(outAlias));
            tommy.move(0, 0);
            terry.move(4, 8);
            tommy.move(3, 4);
            terry.move(2, 5);
            tommy.move(3, 3);
            terry.move(3, 3);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    在这里插入图片描述

    格式化修饰符 %s 表明这里需要 String 参数。

    所有的 tommy 都将输出到 System.out,而所有的 terry 则都输出到 System.out 的一个别名中。Formatter 的重载构造器支持输出到多个路径,不过最常用的还是 PrintStream()(如上例)、OutputStreamFile

    格式化修饰符

    在插入数据时,如果想要优化空格与对齐,你需要更精细复杂的格式修饰符。以下是其通用语法:

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

    最常见的应用是控制一个字段的最小长度,这可以通过指定 width 来实现。Formatter对象通过在必要时添加空格,来确保一个字段至少达到设定长度。默认情况下,数据是右对齐的,不过可以通过使用 - 标志来改变对齐方向。

    width 相对的是 precision,用于指定最大长度。width 可以应用于各种类型的数据转换,并且其行为方式都一样。precision 则不然,当应用于不同类型的数据转换时,precision 的意义也不同。在将 precision 应用于 String 时,它表示打印 string 时输出字符的最大数量。而在将 precision 应用于浮点数时,它表示小数部分要显示出来的位数(默认是 6 位小数),如果小数位数过多则舍入,太少则在尾部补零。由于整数没有小数部分,所以 precision 无法应用于整数,如果你对整数应用 precision,则会触发异常。

    下面的程序应用格式修饰符来打印一个购物收据。这是 Builder 设计模式的一个简单实现,即先创建一个初始对象,然后逐渐添加新东西,最后调用 build() 方法完成构建:

    import java.util.*;
    
    public class ReceiptBuilder {
        private double total = 0;
        private Formatter f = new Formatter(new StringBuilder());
    
        public ReceiptBuilder() {
            f.format("%-15s %5s %10s%n", "Item", "Qty", "Price");
            f.format("%-15s %5s %10s%n", "----", "---", "-----");
        }
    
        public void add(String name, int qty, double price) {
            f.format("%-15.15s %5d %10.2f%n", name, qty, price);
            total += price * qty;
        }
    
        public String build() {
            f.format("%-15s %5s %10.2f%n", "Tax", "",total * 0.06);
            f.format("%-15s %5s %10s%n", "", "", "-----");
            f.format("%-15s %5s %10.2f%n", "Total", "",total * 1.06);
            return f.toString();
        }
    
        public static void main(String[] args) {
            ReceiptBuilder receiptBuilder = new ReceiptBuilder();
            receiptBuilder.add("Jack's Magic Beans", 4, 4.25);
            receiptBuilder.add("Princess Peas", 3, 5.1);
            receiptBuilder.add("Three Bears Porridge", 1, 14.29);
            System.out.println(receiptBuilder.build());
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    在这里插入图片描述

    通过传入一个 StringBuilder 对象到 Formatter 的构造器,我们指定了一个容器来构建目标 String。你也可以通过不同的构造器参数,把结果输出到标准输出,甚至是一个文件里。

    正如你所见,通过相当简洁的语法,Formatter 提供了对空格与对齐的强大控制能力。在该程序中,为了恰当地控制间隔,格式化字符串被重复利用了多遍。

    Formatter 转换

    下面的表格展示了最常用的类型转换:

    类型含义
    d整型(十进制)
    cUnicode字符
    bBoolean值
    sString
    f浮点数(十进制)
    e浮点数(科学计数)
    x整型(十六进制)
    h散列码(十六进制)
    %字面值“%”

    下面的程序演示了这些转换是如何工作的:

    import java.math.*;
    import java.util.*;
    
    public class Conversion {
        public static void main(String[] args) {
            Formatter f = new Formatter(System.out);
    
            char u = 'a';
            System.out.println("u = 'a'");
            f.format("s: %s%n", u);
            // f.format("d: %d%n", u);     
            f.format("c: %c%n", u);
            f.format("b: %b%n", u);
            // f.format("f: %f%n", u);     
            // f.format("e: %e%n", u);     
            // f.format("x: %x%n", u);     
            f.format("h: %h%n", u);
    
            int v = 121;
            System.out.println("v = 121");
            f.format("d: %d%n", v);
            f.format("c: %c%n", v);
            f.format("b: %b%n", v);
            f.format("s: %s%n", v);
            // f.format("f: %f%n", v);     
            // f.format("e: %e%n", v);     
            f.format("x: %x%n", v);
            f.format("h: %h%n", v);
    
            BigInteger w = new BigInteger("50000000000000");
            System.out.println(
                    "w = new BigInteger(\"50000000000000\")");
            f.format("d: %d%n", w);
            // f.format("c: %c%n", w);     
            f.format("b: %b%n", w);
            f.format("s: %s%n", w);
            // f.format("f: %f%n", w);     
            // f.format("e: %e%n", w);     
            f.format("x: %x%n", w);
            f.format("h: %h%n", w);
    
            double x = 179.543;
            System.out.println("x = 179.543");
            // f.format("d: %d%n", x);     
            // f.format("c: %c%n", x);     
            f.format("b: %b%n", x);
            f.format("s: %s%n", x);
            f.format("f: %f%n", x);
            f.format("e: %e%n", x);
            // f.format("x: %x%n", x);     
            f.format("h: %h%n", x);
    
            Conversion y = new Conversion();
            System.out.println("y = new Conversion()");
    
            // f.format("d: %d%n", y);     
            // f.format("c: %c%n", y);     
            f.format("b: %b%n", y);
            f.format("s: %s%n", y);
            // f.format("f: %f%n", y);     
            // f.format("e: %e%n", y);     
            // f.format("x: %x%n", y);     
            f.format("h: %h%n", y);
    
            boolean z = false;
            System.out.println("z = false");
            // f.format("d: %d%n", z);     
            // f.format("c: %c%n", z);     
            f.format("b: %b%n", z);
            f.format("s: %s%n", z);
            // f.format("f: %f%n", z);     
            // f.format("e: %e%n", z);     
            // f.format("x: %x%n", z);     
            f.format("h: %h%n", z);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76

    在这里插入图片描述

    被注释的代码表示,针对相应类型的变量,这些转换是无效的。如果执行这些转换,则会触发异常。

    注意,程序中的每个变量都用到了 b 转换。虽然它对各种类型都是合法的,但其行为却不一定与你想象的一致。对于 boolean 基本类型或 Boolean 对象,其转换结果是对应的 truefalse。但是,对其他类型的参数,只要该参数不为 null,其转换结果永远都是 true。即使是数字 0,转换结果依然为 true,而这在其他语言中(包括C),往往转换为 false。所以,将 b 应用于非布尔类型的对象时请格外小心。

    还有许多不常用的类型转换与格式修饰符选项,你可以在 JDK 文档中的 Formatter 类部分找到它们。

    String.format()

    Java SE5 也参考了 C 中的 sprintf() 方法,以生成格式化的 String 对象。String.format() 是一个 static 方法,它接受与 Formatter.format() 方法一样的参数,但返回一个 String 对象。当你只需使用一次 format() 方法的时候,String.format() 用起来很方便。例如:

    public class DatabaseException extends Exception {
        public DatabaseException(int transactionID, int queryID, String message) {
            super(String.format("(t%d, q%d) %s", transactionID, queryID, message));
        }
    
        public static void main(String[] args) {
            try {
                throw new DatabaseException(3, 7, "Write failed");
            } catch (Exception e) {
                System.out.println(e);
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    在这里插入图片描述

    其实在 String.format() 内部,它也是创建了一个 Formatter 对象,然后将你传入的参数转给 Formatter。不过,与其自己做这些事情,不如使用便捷的 String.format() 方法,何况这样的代码更清晰易读。

    一个十六进制转储(dump)工具

    在第二个例子中,我们把二进制文件转换为十六进制格式。下面的小工具使用了 String.format() 方法,以可读的十六进制格式将字节数组打印出来:

    import java.nio.file.*;
    
    public class Hex {
        public static String format(byte[] data) {
            StringBuilder result = new StringBuilder();
            int n = 0;
            for (byte b : data) {
                if (n % 16 == 0) {
                    result.append(String.format("%05X: ", n));
                }
                result.append(String.format("%02X ", b));
                n++;
                if (n % 16 == 0) {
                    result.append("\n");
                }
            }
            result.append("\n");
            return result.toString();
        }
    
        public static void main(String[] args) throws Exception {
            if (args.length == 0)
            // Test by displaying this class file:
            {
                System.out.println(format(
                        Files.readAllBytes(Paths.get(
                                "D:\\onJava\\test\\src\\main\\java\\com\\example\\test\\Hex.class"))));
            } else {
                System.out.println(format(
                        Files.readAllBytes(Paths.get(args[0]))));
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33

    部分打印截图:
    在这里插入图片描述

    为了打开及读入二进制文件,我们用到了另一个工具 Files.readAllBytes(),这已经在 Files章节 介绍过了。这里的 readAllBytes() 方法将整个文件以 byte 数组的形式返回。

  • 相关阅读:
    猿创征文|Java后端开发,从小白到入门的成长经历
    智能合约漏洞,价值 50 万美元 BNO 攻击事件原理分析
    【批处理DOS-CMD命令-汇总和小结】-将文件夹映射成虚拟磁盘——subst
    yaml
    「聊设计模式」之模板方法模式(Template Method)
    Qwt QwtLegend和QwtPlotLegendItem图例类详解
    HTML5+CSS3小实例:侧边导航栏
    Linux Mint 20 升级到 Linux Mint 21
    pandas中的数据结构
    LNMP架构安装以及部署DISCUZ!社区论坛应用
  • 原文地址:https://blog.csdn.net/GXL_1012/article/details/133959889