如何将文件中的十六进制值读入字节数组?

How to read hex values from file into byte array?

我有一个文件,其中包含注释(看起来像 Java 以双斜杠开头的单行注释,//)和 space 分隔的十六进制值。

文件如下所示:

//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 class.

中为您提供的方法
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 );
    }
}

只是想我要指出的是,如果您稍微放宽规范,您基本上可以在一行中使用 splitAsStream

List<Integer> out = Pattern.compile( "[\s;]+" ).splitAsStream( line )
       .map( Integer::decode ).collect( Collectors.toList() );

我在这里使用 Integer 和 Integer::decode 因为 Byte::decode 会在 OP 的第一个输入 0x80 上抛出错误。如果你真的需要一组基元,你必须做更多的工作,但通常盒装数字在实践中就可以了。

完整代码如下:

public class ScannerStream {

   static String testVector = "//create applet instance\n" +
"0x80 0xB8 0x00 0x00 0x0c 0x0a 0xa0 0x00 0x00 0x00 0x62 0x03 0x01 0xc 0x01 0x01 0x00 0x7F;";

   public static void main( String[] args ) {
      List<List<Integer>> commands = new ArrayList<>();
      Scanner fileReader = new Scanner( new StringReader( testVector ) );
      while( fileReader.hasNextLine() ) {
         String line = fileReader.nextLine();
         if( line.startsWith( "0x" ) ) {
            List<Integer> out = Pattern.compile( "[\s;]+" ).splitAsStream( line )
                    .map( Integer::decode ).collect( Collectors.toList() );
            System.out.println( out );
            commands.add( out );
         }
      }
      System.out.println( commands );
   }
}