Java ByteBuffer to String toString(ByteBuffer buffer)

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

Description

Convert the buffer to an ISO-8859-1 String

License

Open Source License

Parameter

Parameter Description
buffer The buffer to convert in flush mode. The buffer is unchanged

Return

The buffer as a string.

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.Charset;
import java.nio.charset.StandardCharsets;

public class Main {
    /** Convert the buffer to an ISO-8859-1 String
     * @param buffer The buffer to convert in flush mode. The buffer is unchanged
     * @return The buffer as a string./*from w w w  . j  a v  a2s  . c  o m*/
     */
    public static String toString(ByteBuffer buffer) {
        return toString(buffer, StandardCharsets.ISO_8859_1);
    }

    /** Convert the buffer to an ISO-8859-1 String
     * @param buffer  The buffer to convert in flush mode. The buffer is unchanged
     * @param charset The {@link Charset} to use to convert the bytes
     * @return The buffer as a string.
     */
    public static String toString(ByteBuffer buffer, Charset charset) {
        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, charset);
        }
        return new String(array, buffer.arrayOffset() + buffer.position(), buffer.remaining(), charset);
    }

    /** Convert a partial buffer to a String.
     * 
     * @param buffer the buffer to convert 
     * @param position The position in the buffer to start the string from
     * @param length The length of the buffer
     * @param charset The {@link Charset} to use to convert the bytes
     * @return  The buffer as a string.
     */
    public static String toString(ByteBuffer buffer, int position, int length, Charset charset) {
        if (buffer == null)
            return null;
        byte[] array = buffer.hasArray() ? buffer.array() : null;
        if (array == null) {
            ByteBuffer ro = buffer.asReadOnlyBuffer();
            ro.position(position);
            ro.limit(position + length);
            byte[] to = new byte[length];
            ro.get(to);
            return new String(to, 0, to.length, charset);
        }
        return new String(array, buffer.arrayOffset() + position, length, charset);
    }
}

Related

  1. toString(ByteBuffer b, String separator)
  2. toString(ByteBuffer bb)
  3. toString(ByteBuffer buf)
  4. toString(ByteBuffer buf, int len)
  5. toString(ByteBuffer buffer)
  6. toString(ByteBuffer buffer)
  7. toString(ByteBuffer buffer)
  8. toString(ByteBuffer buffer)
  9. toString(ByteBuffer buffer)