Java ByteBuffer Read readShortString(ByteBuffer buffer)

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

Description

read bytes with a short sign prefix(mark the size of bytes)

License

Open Source License

Parameter

Parameter Description
buffer data buffer

Return

string result(encoding with UTF-8)

Declaration

public static String readShortString(ByteBuffer buffer) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.*;

import java.nio.ByteBuffer;

public class Main {
    /**//from  w ww  .jav a  2 s. c  o  m
     * read bytes with a short sign prefix(mark the size of bytes)
     *
     * @param buffer data buffer
     * @return string result(encoding with UTF-8)
     * @see #writeShortString(ByteBuffer, String)
     */
    public static String readShortString(ByteBuffer buffer) {
        short size = buffer.getShort();
        if (size < 0) {
            return null;
        }
        byte[] bytes = new byte[size];
        buffer.get(bytes);
        return fromBytes(bytes);
    }

    public static String fromBytes(byte[] b) {
        return fromBytes(b, "UTF-8");
    }

    public static String fromBytes(byte[] b, String encoding) {
        try {
            return new String(b, encoding);
        } catch (UnsupportedEncodingException e) {
            return new String(b);
        }
    }
}

Related

  1. readReal(ByteBuffer bb)
  2. readResBit15(ByteBuffer fromBuffer)
  3. readShortLE(ByteBuffer buf, int i)
  4. readShortLength(ByteBuffer bb)
  5. readShorts(final ByteBuffer bb, final int length)
  6. readSignedVarint(ByteBuffer buffer)
  7. readSize(ByteBuffer buf)
  8. readSize(ByteBuffer buffer)
  9. readSmart(ByteBuffer buffer)