将ByteBuffer的一部分转换回String

3
我有一个很大的String,曾经被转换为ByteBuffer,后来在多次读取时,只需要呈现部分字符串(文本概述),所以我想仅将ByteBuffer的一部分转换为String。是否可能仅将ByteBuffer的一部分转换为String,而不是[将整个ByteBuffer转换为String,然后使用substring()]?

你实际上无法这样做,因为有些字符占用超过一个字节。 (假设您的字节是UTF-8编码,这是Linux的平台默认值)。 将整个内容转换为“字符串”真的是性能问题吗? - artbristol
我没有对代码进行剖析,但是我只是想尽可能避免解码整个BB。 - Rajat Gupta
2个回答

3
try {
    ByteBuffer bbuf = encoder.encode(CharBuffer.wrap(yourstr));
    bbuf.position(0);
    bbuf.limit(200);
    CharBuffer cbuf = decoder.decode(bbuf);
    String s = cbuf.toString();
    System.out.println(s);
} catch (CharacterCodingException e) {
}

这段代码的意思是从字节缓冲区的第0个字节开始,返回长度为200的字符。

更确切地说:

    ByteBuffer bbuf = ByteBuffer.wrap(yourstr.getBytes());
    bbuf.position(0);
    bbuf.limit(200);

    byte[] bytearr = new byte[bbuf.remaining()];
    bbuf.get(bytearr);
    String s = new String(bytearr);

该功能与显式字符解码/编码无关。

当然,String s 的构造函数会进行解码,但这取决于平台,因此请小心。


我想要获取字符串的前200个字符。我该怎么做? - Rajat Gupta
解码所需的字节数取决于字符集,因此我认为没有通用解决方案。对于UTF-8,您可以解码前800个字节,然后从结果的前200个字符中取一个子字符串。这应该有效,因为UTF-8字符的长度最大为4个字节。 - Soulman

0
// convert all byteBuffer to string
String fullByteBuffer = new String(byteBuffer.array());

// convert part of byteBuffer to string
byte[] partOfByteBuffer = new byte[PART_LENGTH];
System.arraycopy(fullByteBuffer.array(), 0, partOfByteBuffer, 0, partOfByteBuffer.length);
String partOfByteBufferString = new String(partOfByteBuffer.array());

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接