我正在寻找一种从文件中逐行读取十六进制字符串并将它们作为转换后的字节附加到某些 ByteBuffer 的方法。
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
Files.lines(filePath).foreach( l ->
byteBuffer.put(
// first of all strip newlines and normalize string
l.replaceAll("/\n|\r/g", "").toUpperCase()
// but what to do here?
// is there something like
// take next 2 characters (-> Consumer)
// and replace them with the converted byte?
// E.g. "C8" -> 0xC8
// until the end of the string is reached
)
);
这个问题已经被回答了一百万次。但我想知道是否有一个使用 Files.lines()
返回的流的解决方案。
一般来说我喜欢this回答。有人可以帮助我将其转换为基于 java-8 流的解决方案或完成上面的示例吗?
谢谢!
最佳答案
您可以使用实用程序方法将该行解析为十六进制字符串到字节数组:
public static byte[] hexStringToByteArray(String str) {
if(str.startsWith("0x")) { // Get rid of potential prefix
str = str.substring(2);
}
if(str.length() % 2 != 0) { // If string is not of even length
str = '0' + str; // Assume leading zeroes were left out
}
byte[] result = new byte[str.length() / 2];
for(int i = 0; i < str.length(); i += 2) {
String nextByte = str.charAt(i) + "" + str.charAt(i + 1);
// To avoid overflow, parse as int and truncate:
result[i / 2] = (byte) Integer.parseInt(nextByte, 16);
}
return result;
}
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
Files.lines(filePath).forEach( l ->
byteBuffer.put(
hexStringToByteArray(l.replaceAll("/\n|\r/g", "").toUpperCase())
)
);
关于java - 使用 Java 8 流将十六进制字符串转换为 ByteBuffer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50171324/