ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
#### [一个十六进制转储(dump)工具](https://lingcoder.gitee.io/onjava8/#/book/18-Strings?id=%e4%b8%80%e4%b8%aa%e5%8d%81%e5%85%ad%e8%bf%9b%e5%88%b6%e8%bd%ac%e5%82%a8%ef%bc%88dump%ef%bc%89%e5%b7%a5%e5%85%b7) 在第二个例子中,我们把二进制文件转换为十六进制格式。下面的小工具使用了`String.format()`方法,以可读的十六进制格式将字节数组打印出来: ~~~ // strings/Hex.java // {java onjava.Hex} package onjava; import java.io.*; 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( "build/classes/main/onjava/Hex.class")))); else System.out.println(format( Files.readAllBytes(Paths.get(args[0])))); } } /* Output: (First 6 Lines) 00000: CA FE BA BE 00 00 00 34 00 61 0A 00 05 00 31 07 00010: 00 32 0A 00 02 00 31 08 00 33 07 00 34 0A 00 35 00020: 00 36 0A 00 0F 00 37 0A 00 02 00 38 08 00 39 0A 00030: 00 3A 00 3B 08 00 3C 0A 00 02 00 3D 09 00 3E 00 00040: 3F 08 00 40 07 00 41 0A 00 42 00 43 0A 00 44 00 00050: 45 0A 00 14 00 46 0A 00 47 00 48 07 00 49 01 00 ... */ ~~~ 为了打开及读入二进制文件,我们用到了另一个工具`Files.readAllBytes()`,这已经在[Files章节](https://lingcoder.gitee.io/onjava8/#/./17-Files)介绍过了。这里的`readAllBytes()`方法将整个文件以`byte`数组的形式返回。