Here you can find the source of bufferToString(ByteBuffer buf)
public static String bufferToString(ByteBuffer buf)
//package com.java2s; /* USE THIS FILE ACCORDING TO THE COPYRIGHT RULES IN LICENSE.TXT WHICH IS PART OF THE SOURCE CODE PACKAGE */ import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; public class Main { public static String bufferToString(ByteBuffer buf) { try {// ww w . jav a 2s .c o m boolean isString = true; byte[] arr = buf.array(); for (int i = 0; i < buf.remaining(); i++) { byte c = arr[i]; if (c <= 127 || ((c & 0xC0) == 0x80) || ((c & 0xE0) == 0xC0)) continue; isString = false; break; } if (isString) { return new String(buf.array(), 0, buf.remaining(), "UTF-8"); } else { StringBuilder sbuf = new StringBuilder(); sbuf.append("byte[] bytes = new byte[] {"); for (int i = 0; i < buf.remaining(); i++) { if (i != 0) sbuf.append(", "); if ((i % 10) == 0) sbuf.append("\r\n"); sbuf.append("(byte)0x"); int c = arr[i] & 0xFF; String s = Integer.toHexString(c); if (s.length() < 2) sbuf.append("0"); sbuf.append(s); } sbuf.append("};"); return sbuf.toString(); } } catch (UnsupportedEncodingException e) { throw new IllegalStateException(e); } } }