Java ByteBuffer to String toString(ByteBuffer buffer)

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

Description

Convert the ByteBuffer to a UTF-8 String.

License

Open Source License

Parameter

Parameter Description
buffer the buffer to convert

Return

the String form of the buffer

Declaration

public static String toString(ByteBuffer buffer) 

Method Source Code


//package com.java2s;
//  are made available under the terms of the Eclipse Public License v1.0

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

public class Main {
    /**/*from   w  ww .  ja v  a2s  .  c om*/
     * Convert the ByteBuffer to a UTF-8 String.
     *
     * @param buffer the buffer to convert
     * @return the String form of the buffer
     */
    public static String toString(ByteBuffer buffer) {
        if (buffer == null)
            return null;
        byte[] array = buffer.hasArray() ? buffer.array() : null;
        if (array == null) {
            byte[] to = new byte[buffer.remaining()];
            buffer.slice().get(to);
            return new String(to, 0, to.length, StandardCharsets.UTF_8);
        }
        return new String(array, buffer.arrayOffset() + buffer.position(), buffer.remaining(),
                StandardCharsets.UTF_8);
    }
}

Related

  1. toString(ByteBuffer buffer)
  2. toString(ByteBuffer buffer)
  3. toString(ByteBuffer buffer)
  4. toString(ByteBuffer buffer)
  5. toString(ByteBuffer buffer)
  6. toString(ByteBuffer buffer, Charset charset)
  7. toString(ByteBuffer buffer, int offset, int length)
  8. toString(ByteBuffer buffer, String encoding)
  9. toString(ByteBuffer bytes)