Java ByteBuffer to String getString(ByteBuffer buf, Charset encoding)

Here you can find the source of getString(ByteBuffer buf, Charset encoding)

Description

Converts all remaining bytes in the buffer a String using the specified encoding.

License

Apache License

Declaration

public static String getString(ByteBuffer buf, Charset encoding) 

Method Source Code


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

import java.nio.ByteBuffer;
import java.nio.charset.Charset;

public class Main {
    /**// w w  w .  j a  v  a 2s.  c o m
     * Converts all remaining bytes in the buffer a String using the specified encoding.
     * Does not move the buffer position.
     */
    public static String getString(ByteBuffer buf, Charset encoding) {
        return getString(buf, 0, buf.remaining(), encoding);
    }

    /**
     * Converts the specified number of bytes in the buffer and converts them to a String using
     * the specified encoding.  Does not move the buffer position.
     */
    public static String getString(ByteBuffer buf, int offset, int length, Charset encoding) {
        buf = buf.duplicate();
        buf.position(buf.position() + offset);
        if (buf.hasArray()) {
            return new String(buf.array(), buf.arrayOffset() + buf.position(), length, encoding);
        } else {
            byte[] bytes = new byte[length];
            buf.get(bytes);
            return new String(bytes, encoding);
        }
    }
}

Related

  1. getString(@Nonnull final ByteBuffer src)
  2. getString(ByteBuffer bb)
  3. getString(ByteBuffer buf)
  4. getString(ByteBuffer buf)
  5. getString(ByteBuffer buf)
  6. getString(ByteBuffer buf, int length, String charsetName)
  7. getString(ByteBuffer buffer)
  8. getString(ByteBuffer buffer)
  9. getString(ByteBuffer buffer, int length)