Java ByteBuffer to String readString(ByteBuffer buff)

Here you can find the source of readString(ByteBuffer buff)

Description

read String

License

LGPL

Declaration

public static String readString(ByteBuffer buff) 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;

public class Main {
    public static String readString(ByteBuffer buff) {
        int size = readVarInt(buff);
        byte[] bytes = new byte[size];
        buff.get(bytes);/*from  w w  w .ja  v  a2 s. c  o m*/
        return new String(bytes, StandardCharsets.UTF_8);
    }

    /**
     * Reads a VarInt.
     *
     * @return the int value
     */
    public static int readVarInt(ByteBuffer buff) {
        int shift = 0, i = 0;
        while (true) {
            byte b = (byte) buff.get();
            i |= (b & 0x7F) << shift;// Remove sign bit and shift to get the next 7 bits
            shift += 7;
            if (b >= 0) {// VarInt byte prefix is 0, it means that we just decoded the last 7 bits, therefore we've
                // finished.
                return i;
            }
        }
    }
}

Related

  1. readString(ByteBuffer bb)
  2. readString(ByteBuffer bb)
  3. readString(ByteBuffer bb, int limit)
  4. readString(ByteBuffer buf)
  5. readString(ByteBuffer buf, int length)
  6. readString(ByteBuffer buff, int len)
  7. readString(ByteBuffer buffer)
  8. readString(ByteBuffer buffer)
  9. readString(ByteBuffer byteBuffer)