我有一个很大的String,曾经被转换为ByteBuffer,后来在多次读取时,只需要呈现部分字符串(文本概述),所以我想仅将ByteBuffer的一部分转换为String。是否可能仅将ByteBuffer的一部分转换为String,而不是[将整个ByteBuffer转换为String,然后使用substring()]?
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
的构造函数会进行解码,但这取决于平台,因此请小心。
// 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());