Java 深究字符串String类(3)format()静态方法

1.Formatter类

这有个Formatter类其实是一个翻译器,将格式化字符串翻译成需要的结果,
简单例子:

 public static void main(String[] args) {
        String a = "West World";
        Formatter f = new Formatter(System.err);
        f.format("this is the %s\n", a);
    }

这样就把输出,出到标准error里了~

Formatter的构造器经过重载可以接受多种输出目的地,最常用的还是PrintStream,OutputStream,File之类的.

2.String.format()静态方法

仿照c语言sprintf() 生成格式化String对象

例子:

public class Four extends Exception {


    public Four(String errMess, int x, int y) {
        super(String.format("(%d, %d) %s\n", x, y, errMess));
    }

    public static void main(String[] args) {
        try {
            throw new Four("Memery Error",123, 456);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

实际上String.format()内部,创建一个Formatter对象,然后将参数传给Formatter

3.一个十六进制dump工具

package net.mindview.utl;

import java.io.File;

public class Hex {
    public static String formate(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) {
        if(args.length == 0) System.out.println(BinaryFile.read("Hex.class"));
        else System.out.println(formate(BinaryFile.read(new File(args[0]))));
    }
}

待续–

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值