Java ByteBuffer to String toString(final ByteBuffer buffer)

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

Description

Returns the buffer as a string while preserving the buffer position and limit.

License

Open Source License

Parameter

Parameter Description
buffer The buffer to create a string from.

Return

The buffer string.

Declaration

public static String toString(final ByteBuffer buffer) 

Method Source Code

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

import java.nio.ByteBuffer;
import java.util.Collection;
import java.util.Iterator;

public class Main {
    /**/*w  w  w.  ja  va 2s .c  o  m*/
     * Returns the buffer as a string while preserving the buffer position and
     * limit.
     * 
     * @param buffer
     *            The buffer to create a string from.
     * @return The buffer string.
     */
    public static String toString(final ByteBuffer buffer) {
        final int position = buffer.position();
        final int limit = buffer.limit();
        final byte[] data = new byte[buffer.remaining()];
        buffer.get(data);

        final String dataString = new String(data);

        buffer.position(position);
        buffer.limit(limit);

        return dataString;
    }

    public static int remaining(final Collection<ByteBuffer> buffers) {
        int remaining = 0;
        for (final Iterator iter = buffers.iterator(); iter.hasNext();) {
            final ByteBuffer buf = (ByteBuffer) iter.next();
            remaining += buf.remaining();
        }
        return remaining;
    }
}

Related

  1. toString(ByteBuffer buffer, String encoding)
  2. toString(ByteBuffer bytes)
  3. toString(ByteBuffer bytes)
  4. toString(ByteBuffer sequence)
  5. toString(ByteBuffer value, String charsetName)
  6. toString(final ByteBuffer buffer)
  7. toString(final ByteBuffer buffer)
  8. toStringBinary(ByteBuffer buf)
  9. toStringBinary(ByteBuffer buf)