【问题标题】:Convert a part of ByteBuffer back to String将 ByteBuffer 的一部分转换回 String
【发布时间】:2012-06-26 07:53:18
【问题描述】:

我有一个很大的String,它曾经被转换为ByteBuffer,然后在稍后阅读几次时,只需要呈现String的一部分(文本概述),所以我想仅将ByteBuffer 的一部分转换为String

是否可以仅将字节缓冲区的一部分转换为字符串,而不是[将整个Bytebuffer 转换为String & 然后使用substring()]

【问题讨论】:

  • 你不能真正做到这一点,因为有些字符占用超过一个字节。 (假设您的字节是 UTF-8 编码的,Linux 的平台默认值)。将全部转换成String真的是性能问题吗?
  • 我没有分析我的代码,但我只是想避免解码整个 BB如果可能的话

标签: java string bytebuffer


【解决方案1】:
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 个字符。我该怎么做?
  • 要解码的字节数取决于字符集,所以我认为没有通用的解决方案。对于 UTF-8,您可以解码前 800 个字节,然后获取结果的前 200 个字符的子字符串。这应该可以工作,因为 UTF-8 字符的长度最多为 4 个字节。
【解决方案2】:
// 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());

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-18
    相关资源
    最近更新 更多