java - 如何将文件中的十六进制值读取到字节数组中?

标签 java java.util.scanner filereader

我有一个由注释(看起来像 Java 单行注释,以双斜杠 // 开头)和空格分隔的十六进制值组成的文件。

文件如下所示:

//create applet instance
0x80 0xB8 0x00 0x00 0x0c 0x0a 0xa0 0x00 0x00 0x00 0x62 0x03 0x01 0xc 0x01 0x01 0x00 0x7F;

如何将十六进制值从字符串转换为字节数组的行?

我使用以下方法:

List<byte[]> commands = new ArrayList<>();
Scanner fileReader = new Scanner(new FileReader(file));
while (fileReader.hasNextLine()) {
      String line = fileReader.nextLine();
      if (line.startsWith("0x")) {
          commands.add(line.getBytes());
      }
}

但可以肯定的是,这显示了符号的字节表示形式,因为它们是字符,并且不会将其转换为字节。这是正确的。但如何才能正确转换呢?

提前致谢。

最佳答案

你走在正确的道路上。只需删除尾随的 ;,然后使用 Integer 类中为您提供的方法即可。

while ( fileReader.hasNextLine() ) {
    String line = fileReader.nextLine();
    if ( line.startsWith( "0x" ) ) {
        line = line.replace( ";", "" );
        List<Byte> wrapped = Arrays
                .asList( line.split( " " ) )
                .stream()
                // convert all the string representations to their Int value
                .map( Integer::decode )
                // convert all the Integer values to their byte value
                .map( Integer::byteValue )
                .collect( Collectors.toList() );
        // if you're OK with changing commands to a List<Byte[]>, you can skip this step
        byte[] toAdd = new byte[wrapped.size()];
        for ( int i = 0; i < toAdd.length; i++ ) {
            toAdd[i] = wrapped.get( i );
        }
        commands.add( toAdd );
    }
}

关于java - 如何将文件中的十六进制值读取到字节数组中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53729021/

相关文章:

java - 为什么 Slick 向我发出有关 PNG 数据的警告?

java - 分配参数类型对整数溢出的影响

java - java - 如何声明数组而不必在java中给出固定的初始大小?

java - Java 扫描器类

循环中的 Java 扫描器仅获取第一个输入

javascript - Chrome 文件阅读器的 PC8/CP437 字符集

Javascript,使用 Promises 在 Array.reduce 中上传多个文件,怎么样?

javascript - 在 php 上传之前使用 FileReader 调整多个图像的大小

java - Android 中的 GSON/Jackson

java - 如何在ArrayList中找到重复次数最多的字符串?