Java ByteBuffer convert to String by CharsetDecoder
import java.nio.ByteBuffer; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CodingErrorAction; import java.util.Arrays; public class Main { public static void main(String[] argv) throws Exception { ByteBuffer bb = ByteBuffer.wrap("demo2s.com".getBytes()); System.out.println(Arrays.toString(toArray(bb))); bb.flip();//from w w w . ja v a 2 s .com CharSequence string = getCharSequence(bb, Charset.defaultCharset().newDecoder()); System.out.println(string); } public static CharSequence getCharSequence(final ByteBuffer buf, final CharsetDecoder decoder) { final ByteBuffer buffer = buf.slice(); // Find the NUL terminator and limit to that, so the // StringBuffer/StringBuilder does not have superfluous NUL chars int end = indexOf(buffer, (byte) 0); if (end < 0) { end = buffer.limit(); } buffer.position(0).limit(end); try { return decoder.reset().onMalformedInput(CodingErrorAction.REPLACE) .onUnmappableCharacter(CodingErrorAction.REPLACE).decode(buffer); } catch (CharacterCodingException ex) { throw new Error("Illegal character data in native string", ex); } } public static int indexOf(ByteBuffer buf, byte value) { if (buf.hasArray()) { byte[] array = buf.array(); int begin = buf.arrayOffset() + buf.position(); int end = buf.arrayOffset() + buf.limit(); for (int offset = 0; offset < end && offset > -1; ++offset) { if (array[begin + offset] == value) { return offset; } } } else { int begin = buf.position(); for (int offset = 0; offset < buf.limit(); ++offset) { if (buf.get(begin + offset) == value) { return offset; } } } return -1; } public static byte[] toArray(final ByteBuffer buffer) { byte[] array = new byte[buffer.limit()]; buffer.get(array); return array; } }