2012-06-26 117 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());