我有一个由注释(看起来像 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/