java - 使用 Java 8 流将十六进制字符串转换为 ByteBuffer

标签 java java-8 java-stream string-conversion

我正在寻找一种从文件中逐行读取十六进制字符串并将它们作为转换后的字节附加到某些 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/

相关文章:

Java 8 获取列表中的所有元素

java - 在try-with-resources中声明的变量的注释?

java - 如何使用 Java 8 流过滤列表并从值数组开始

java - 如何在 Java 8 中检查 Stream<String> 是否包含另一个 Stream<String>

java - 流式定义

java - "constructor statement"和 "declaration statement"是描述这些语句的正确名称吗?

java - mvn clean install 抛出错误 - 文件之前未被格式化。请在运行验证之前格式化文件并提交

java - swing:关于调整 JFrame 大小和条件滚动

java - WCF与java客户端双向通信

java - 如何将字符串列表转换为 LinkedHashMap?