符。

import java.io.FileInputStream;
import java.io.IOException;

public class HexViewer {
    public static void main(String[] args) {
        if (args.length == 0) {
            System.out.println("Usage: java HexViewer <filename>");
            return;
        }
        
        String filename = args[0];
        try (FileInputStream fis = new FileInputStream(filename)) {
            int b;
            while ((b = fis.read()) != -1) {
                System.out.printf("%02X", b);
            }
        } catch (IOException e) {
            System.err.println("Failed to read file: " + filename);
            e.printStackTrace();
        }
    }
}

使用示例:

$ java HexViewer myfile.txt
48656C6C6F20776F726C6421

上述代码中,使用了 try-with-resources 语句来自动关闭文件流。在读取文件时,每次读取一个字节,然后以十六进制形式显示在标准输出上,使用了 printf 方法来控制输出格式。注意在输出时要用大写字母表示十六进制数字

用java编写一程序由用户输入任一文件依次读取文件内容的每一个字节以十六进制形式显示在标准输出上字节之间无分隔

原文地址: https://www.cveoy.top/t/topic/e9xM 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录