Java ByteBuffer to String readString(ByteBuffer buffer)

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

Description

read String

License

Open Source License

Declaration

public static String readString(ByteBuffer buffer) throws IOException 

Method Source Code


//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;
    }
}

Related

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