Here you can find the source of readString(ByteBuffer buffer)
public static String readString(ByteBuffer buffer) throws IOException
//package com.java2s; //License from project: Open Source License import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; public class Main { private static final int MAX_STRING_LENGTH = Short.MAX_VALUE >> 2; public static String readString(ByteBuffer buffer) throws IOException { int i = readVarInt(buffer); if (i > MAX_STRING_LENGTH * 4) { throw new IOException("The received encoded string buffer length is longer than maximum allowed (" + i + " > " + MAX_STRING_LENGTH * 4 + ")"); }//from w w w .ja v a 2s .c om if (i < 0) { throw new IOException("The received encoded string buffer length is less than zero! Weird string!"); } try { byte[] bytes = new byte[i]; buffer.get(bytes); String s = new String(bytes, StandardCharsets.UTF_8); if (s.length() > MAX_STRING_LENGTH) { throw new IOException("The received string length is longer than maximum allowed (" + s.length() + " > " + MAX_STRING_LENGTH + ")"); } else { return s; } } catch (UnsupportedEncodingException e) { throw new IOException(e); } } public static int readVarInt(ByteBuffer buffer) throws IOException { int i = 0; int j = 0; while (true) { int b0 = buffer.get(); i |= (b0 & 127) << j++ * 7; if (j > 5) { throw new IOException("VarInt too big"); } if ((b0 & 128) != 128) { break; } } return i; } }