从ByteBuffer读取UTF-8字符串,其中length是unsigned int

Tof*_*eer 1 java string bytebuffer utf-8

我试图通过java.nio.ByteBuffer读取UTF8字符串.大小是一个unsinged int,当然,Java没有.我已经把这个值读成了很长的一段时间,所以我有了价值.

我的下一个问题是我不能用long创建一个字节数组,并且他长期回到int会导致它被签名.

我也尝试在缓冲区上使用limit(),但是再次使用int不长.

我正在做的具体事情是从类文件中读取UTF8字符串,因此缓冲区中只有UTF8字符串.

关于如何从ByteBuffer读取具有潜在长度的unsigned int的UTF8字符串的任何想法.

编辑:

这是一个问题的例子.

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.
Run Code Online (Sandbox Code Playgroud)

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

如果对UTF8字符串的大小有限制,这些不会成为问题(我不是UTF8专家,所以可能存在这样的限制).

我可以在它上面扯下它,并与现实一致,那就是不会有一个很长的字符串......

Aln*_*tak 6

除非你的字节数组超过2GB(Java的最大正值int),否则将long后面的数据转换为有符号数字就不会有问题int.

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