在此程序中,我们逐字节读取文件内容,然后以十六进制格式打印该值。作为读取单个字节的替代方法,我们可以一次将文件内容读取到字节数组中,以更快地处理文件。package org.nhooo.example.io;
import java.io.FileInputStream;
public class HexDumpDemo {
public static void main(String[] args) throws Exception {
// 使用FileInputStream打开文件
try (FileInputStream fis = new FileInputStream("C:/Users/nhooo/data.txt")) {
// 用于保存文件数据单个字节的变量
int i = 0;
// 一个计数器,每读取16个字节就打印一个新行。
int count = 0;
// 读取到文件末尾并以十六进制打印字节
// 价值
while ((i = fis.read()) != -1) {
System.out.printf("%02X ", i);
count++;
if (count == 16) {
System.out.println("");
count = 0;
}
}
}
}
}
这是上述程序读取的文件的一些结果。31 32 33 34 35 36 37 38 39 30 31 32 33 34 35 36
37 38 39 30 31 32 33 34 35 36 37 38 39 30 31 32
33 34 35 36 37 38 39 30 31 32 33 34 35 36 37 38
39 30 31 32 33 34 35 36 37 38 39 30 31 32 33 34
35 36 37 38 39 30 0A