2012-06-26 61 views
1

我有一个大String曾一度转化为ByteBuffer &然后在阅读后几次,需要提交只有String(文字概述)的一部分,所以我只想将ByteBuffer的一部分转换为String转换字节缓冲区的一部分返回字符串

是否有可能只字节缓冲区的一部分转换为字符串,而不是[转换整个BytebufferString &然后使用substring()]

+0

你不能这样做,因为某些字符占用了多个字节。 (假设你的字节是UTF-8编码的,Linux的平台默认)。把整个转换成一个'String'真的是一个性能问题吗? – artbristol

+0

我没有分析我的代码,但我只是想避免解码整个BB _if possible_ –

回答

2
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); 

其中d但是没有明确的字符解码/编码。

解码当然确实发生在String s的构造函数中,因此需要注意平台。

+0

我想检索字符串的_first 200 characters_。我会怎么做? –

+0

要解码的字节数取决于字符集,所以我不认为有一个通用的解决方案。对于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()); 
相关问题