java - 从长度为 unsigned int 的 ByteBuffer 中读取 UTF-8 字符串

标签 java string utf-8 bytebuffer

我正在尝试通过 java.nio.ByteBuffer 读取 UTF8 字符串。大小是一个 unsinged int,当然,Java 没有。我把值读成long,这样我就有了值。

我遇到的下一个问题是我无法使用 long 创建字节数组,将 long 转换回 int 将导致它被签名。

我也试过在缓冲区上使用 limit(),但它同样不能与 int 一起使用。

我正在做的具体事情是从类文件中读取 UTF8 字符串,因此缓冲区中包含的不仅仅是 UTF8 字符串。

关于如何从 ByteBuffer 中读取可能长度为 unsigned int 的 UTF8 字符串的任何想法。

编辑:

Here is an example of the issue .

SourceDebugExtension_attribute {
       u2 attribute_name_index;
       u4 attribute_length;
       u1 debug_extension[attribute_length];
    }

attribute_name_index
    The value of the attribute_name_index item must be a valid index into the constant_pool table. The constant_pool entry at that index must be a CONSTANT_Utf8_info structure representing the string "SourceDebugExtension".

attribute_length
    The value of the attribute_length item indicates the length of the attribute, excluding the initial six bytes. The value of the attribute_length item is thus the number of bytes in the debug_extension[] item.

debug_extension[]
    The debug_extension array holds a string, which must be in UTF-8 format. There is no terminating zero byte.

    The string in the debug_extension item will be interpreted as extended debugging information. The content of this string has no semantic effect on the Java Virtual Machine.

因此,从技术的角度来看,类文件中的字符串可以是完整的 u4(无符号,4 字节)长度。

如果 UTF8 字符串的大小有限制,这些就不是问题(我不是 UTF8 专家,所以可能有这样的限制)。

我可以赌一把,接受不会有那么长的字符串的现实……

最佳答案

除非您的字节数组超过 2GB(Java int 的最大正值),否则将 long 转换回一个带符号的 int

如果您的字节数组的长度需要超过 2GB,那么您做错了,尤其是因为这远远超过了 JVM 的默认最大堆大小...

关于java - 从长度为 unsigned int 的 ByteBuffer 中读取 UTF-8 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/624207/

相关文章:

java - 使用层次结构数据动态创建 json 文件

c++ - C++中字符串的加法和乘法

objective-c - 字符串常量和字符串文字有什么区别?

mysql - database.yml 中的 utf8 编码问题在插入时丢弃字符串

vba - VBA IDE 中长字符串的格式

java - 为什么 Java 中 (Integer) 222 != (Integer) 222 ?

java - 在 Java 中初始化对象数组/vector 的最简单方法

python - 向字符串添加简单值

utf-8 - 找出 straèe 的字符编码

java - 为什么在使用 G1 GC 时推荐使用 Java 10?