Java ByteBuffer convert remaining byte buffer to String by UTF-8
import java.nio.ByteBuffer; import java.nio.charset.Charset; public class Main { public static void main(String[] argv) throws Exception { ByteBuffer buf = ByteBuffer.wrap("demo2s.com".getBytes()); String a = toTextRemaining(buf); System.out.println(a);/*from w w w . j a va2s. c o m*/ } private static final Charset UTF8 = Charset.forName("UTF-8"); /** * Convert remaining byte buffer to UTF-8 String. * * @param bytes * Source byte buffer. * @return String expression of the bytes. */ public static String toTextRemaining(ByteBuffer bytes) { return new String(toBytesRemaining(bytes), UTF8); } /** * Convert remaining byte buffer to byte array. * * @param buffer * Source byte buffer * @return Remaining byte array. */ public static byte[] toBytesRemaining(ByteBuffer buffer) { byte[] array = new byte[buffer.remaining()]; buffer.get(array); return array; } }